home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.5 / decimal.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-05-11  |  85.0 KB  |  3,115 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''
  5. This is a Py2.3 implementation of decimal floating point arithmetic based on
  6. the General Decimal Arithmetic Specification:
  7.  
  8.     www2.hursley.ibm.com/decimal/decarith.html
  9.  
  10. and IEEE standard 854-1987:
  11.  
  12.     www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
  13.  
  14. Decimal floating point has finite precision with arbitrarily large bounds.
  15.  
  16. The purpose of the module is to support arithmetic using familiar
  17. "schoolhouse" rules and to avoid the some of tricky representation
  18. issues associated with binary floating point.  The package is especially
  19. useful for financial applications or for contexts where users have
  20. expectations that are at odds with binary floating point (for instance,
  21. in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
  22. of the expected Decimal("0.00") returned by decimal floating point).
  23.  
  24. Here are some examples of using the decimal module:
  25.  
  26. >>> from decimal import *
  27. >>> setcontext(ExtendedContext)
  28. >>> Decimal(0)
  29. Decimal("0")
  30. >>> Decimal("1")
  31. Decimal("1")
  32. >>> Decimal("-.0123")
  33. Decimal("-0.0123")
  34. >>> Decimal(123456)
  35. Decimal("123456")
  36. >>> Decimal("123.45e12345678901234567890")
  37. Decimal("1.2345E+12345678901234567892")
  38. >>> Decimal("1.33") + Decimal("1.27")
  39. Decimal("2.60")
  40. >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
  41. Decimal("-2.20")
  42. >>> dig = Decimal(1)
  43. >>> print dig / Decimal(3)
  44. 0.333333333
  45. >>> getcontext().prec = 18
  46. >>> print dig / Decimal(3)
  47. 0.333333333333333333
  48. >>> print dig.sqrt()
  49. 1
  50. >>> print Decimal(3).sqrt()
  51. 1.73205080756887729
  52. >>> print Decimal(3) ** 123
  53. 4.85192780976896427E+58
  54. >>> inf = Decimal(1) / Decimal(0)
  55. >>> print inf
  56. Infinity
  57. >>> neginf = Decimal(-1) / Decimal(0)
  58. >>> print neginf
  59. -Infinity
  60. >>> print neginf + inf
  61. NaN
  62. >>> print neginf * inf
  63. -Infinity
  64. >>> print dig / 0
  65. Infinity
  66. >>> getcontext().traps[DivisionByZero] = 1
  67. >>> print dig / 0
  68. Traceback (most recent call last):
  69.   ...
  70.   ...
  71.   ...
  72. DivisionByZero: x / 0
  73. >>> c = Context()
  74. >>> c.traps[InvalidOperation] = 0
  75. >>> print c.flags[InvalidOperation]
  76. 0
  77. >>> c.divide(Decimal(0), Decimal(0))
  78. Decimal("NaN")
  79. >>> c.traps[InvalidOperation] = 1
  80. >>> print c.flags[InvalidOperation]
  81. 1
  82. >>> c.flags[InvalidOperation] = 0
  83. >>> print c.flags[InvalidOperation]
  84. 0
  85. >>> print c.divide(Decimal(0), Decimal(0))
  86. Traceback (most recent call last):
  87.   ...
  88.   ...
  89.   ...
  90. InvalidOperation: 0 / 0
  91. >>> print c.flags[InvalidOperation]
  92. 1
  93. >>> c.flags[InvalidOperation] = 0
  94. >>> c.traps[InvalidOperation] = 0
  95. >>> print c.divide(Decimal(0), Decimal(0))
  96. NaN
  97. >>> print c.flags[InvalidOperation]
  98. 1
  99. >>>
  100. '''
  101. __all__ = [
  102.     'Decimal',
  103.     'Context',
  104.     'DefaultContext',
  105.     'BasicContext',
  106.     'ExtendedContext',
  107.     'DecimalException',
  108.     'Clamped',
  109.     'InvalidOperation',
  110.     'DivisionByZero',
  111.     'Inexact',
  112.     'Rounded',
  113.     'Subnormal',
  114.     'Overflow',
  115.     'Underflow',
  116.     'ROUND_DOWN',
  117.     'ROUND_HALF_UP',
  118.     'ROUND_HALF_EVEN',
  119.     'ROUND_CEILING',
  120.     'ROUND_FLOOR',
  121.     'ROUND_UP',
  122.     'ROUND_HALF_DOWN',
  123.     'setcontext',
  124.     'getcontext',
  125.     'localcontext']
  126. import copy as _copy
  127. ROUND_DOWN = 'ROUND_DOWN'
  128. ROUND_HALF_UP = 'ROUND_HALF_UP'
  129. ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
  130. ROUND_CEILING = 'ROUND_CEILING'
  131. ROUND_FLOOR = 'ROUND_FLOOR'
  132. ROUND_UP = 'ROUND_UP'
  133. ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
  134. NEVER_ROUND = 'NEVER_ROUND'
  135. ALWAYS_ROUND = 'ALWAYS_ROUND'
  136.  
  137. class DecimalException(ArithmeticError):
  138.     """Base exception class.
  139.  
  140.     Used exceptions derive from this.
  141.     If an exception derives from another exception besides this (such as
  142.     Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
  143.     called if the others are present.  This isn't actually used for
  144.     anything, though.
  145.  
  146.     handle  -- Called when context._raise_error is called and the
  147.                trap_enabler is set.  First argument is self, second is the
  148.                context.  More arguments can be given, those being after
  149.                the explanation in _raise_error (For example,
  150.                context._raise_error(NewError, '(-x)!', self._sign) would
  151.                call NewError().handle(context, self._sign).)
  152.  
  153.     To define a new exception, it should be sufficient to have it derive
  154.     from DecimalException.
  155.     """
  156.     
  157.     def handle(self, context, *args):
  158.         pass
  159.  
  160.  
  161.  
  162. class Clamped(DecimalException):
  163.     '''Exponent of a 0 changed to fit bounds.
  164.  
  165.     This occurs and signals clamped if the exponent of a result has been
  166.     altered in order to fit the constraints of a specific concrete
  167.     representation. This may occur when the exponent of a zero result would
  168.     be outside the bounds of a representation, or  when a large normal
  169.     number would have an encoded exponent that cannot be represented. In
  170.     this latter case, the exponent is reduced to fit and the corresponding
  171.     number of zero digits are appended to the coefficient ("fold-down").
  172.     '''
  173.     pass
  174.  
  175.  
  176. class InvalidOperation(DecimalException):
  177.     '''An invalid operation was performed.
  178.  
  179.     Various bad things cause this:
  180.  
  181.     Something creates a signaling NaN
  182.     -INF + INF
  183.      0 * (+-)INF
  184.      (+-)INF / (+-)INF
  185.     x % 0
  186.     (+-)INF % x
  187.     x._rescale( non-integer )
  188.     sqrt(-x) , x > 0
  189.     0 ** 0
  190.     x ** (non-integer)
  191.     x ** (+-)INF
  192.     An operand is invalid
  193.     '''
  194.     
  195.     def handle(self, context, *args):
  196.         if args:
  197.             if args[0] == 1:
  198.                 return Decimal((args[1]._sign, args[1]._int, 'n'))
  199.             
  200.         
  201.         return NaN
  202.  
  203.  
  204.  
  205. class ConversionSyntax(InvalidOperation):
  206.     '''Trying to convert badly formed string.
  207.  
  208.     This occurs and signals invalid-operation if an string is being
  209.     converted to a number and it does not conform to the numeric string
  210.     syntax. The result is [0,qNaN].
  211.     '''
  212.     
  213.     def handle(self, context, *args):
  214.         return (0, (0,), 'n')
  215.  
  216.  
  217.  
  218. class DivisionByZero(DecimalException, ZeroDivisionError):
  219.     '''Division by 0.
  220.  
  221.     This occurs and signals division-by-zero if division of a finite number
  222.     by zero was attempted (during a divide-integer or divide operation, or a
  223.     power operation with negative right-hand operand), and the dividend was
  224.     not zero.
  225.  
  226.     The result of the operation is [sign,inf], where sign is the exclusive
  227.     or of the signs of the operands for divide, or is 1 for an odd power of
  228.     -0, for power.
  229.     '''
  230.     
  231.     def handle(self, context, sign, double = None, *args):
  232.         if double is not None:
  233.             return (Infsign[sign],) * 2
  234.         
  235.         return Infsign[sign]
  236.  
  237.  
  238.  
  239. class DivisionImpossible(InvalidOperation):
  240.     '''Cannot perform the division adequately.
  241.  
  242.     This occurs and signals invalid-operation if the integer result of a
  243.     divide-integer or remainder operation had too many digits (would be
  244.     longer than precision). The result is [0,qNaN].
  245.     '''
  246.     
  247.     def handle(self, context, *args):
  248.         return (NaN, NaN)
  249.  
  250.  
  251.  
  252. class DivisionUndefined(InvalidOperation, ZeroDivisionError):
  253.     '''Undefined result of division.
  254.  
  255.     This occurs and signals invalid-operation if division by zero was
  256.     attempted (during a divide-integer, divide, or remainder operation), and
  257.     the dividend is also zero. The result is [0,qNaN].
  258.     '''
  259.     
  260.     def handle(self, context, tup = None, *args):
  261.         if tup is not None:
  262.             return (NaN, NaN)
  263.         
  264.         return NaN
  265.  
  266.  
  267.  
  268. class Inexact(DecimalException):
  269.     '''Had to round, losing information.
  270.  
  271.     This occurs and signals inexact whenever the result of an operation is
  272.     not exact (that is, it needed to be rounded and any discarded digits
  273.     were non-zero), or if an overflow or underflow condition occurs. The
  274.     result in all cases is unchanged.
  275.  
  276.     The inexact signal may be tested (or trapped) to determine if a given
  277.     operation (or sequence of operations) was inexact.
  278.     '''
  279.     pass
  280.  
  281.  
  282. class InvalidContext(InvalidOperation):
  283.     '''Invalid context.  Unknown rounding, for example.
  284.  
  285.     This occurs and signals invalid-operation if an invalid context was
  286.     detected during an operation. This can occur if contexts are not checked
  287.     on creation and either the precision exceeds the capability of the
  288.     underlying concrete representation or an unknown or unsupported rounding
  289.     was specified. These aspects of the context need only be checked when
  290.     the values are required to be used. The result is [0,qNaN].
  291.     '''
  292.     
  293.     def handle(self, context, *args):
  294.         return NaN
  295.  
  296.  
  297.  
  298. class Rounded(DecimalException):
  299.     '''Number got rounded (not  necessarily changed during rounding).
  300.  
  301.     This occurs and signals rounded whenever the result of an operation is
  302.     rounded (that is, some zero or non-zero digits were discarded from the
  303.     coefficient), or if an overflow or underflow condition occurs. The
  304.     result in all cases is unchanged.
  305.  
  306.     The rounded signal may be tested (or trapped) to determine if a given
  307.     operation (or sequence of operations) caused a loss of precision.
  308.     '''
  309.     pass
  310.  
  311.  
  312. class Subnormal(DecimalException):
  313.     '''Exponent < Emin before rounding.
  314.  
  315.     This occurs and signals subnormal whenever the result of a conversion or
  316.     operation is subnormal (that is, its adjusted exponent is less than
  317.     Emin, before any rounding). The result in all cases is unchanged.
  318.  
  319.     The subnormal signal may be tested (or trapped) to determine if a given
  320.     or operation (or sequence of operations) yielded a subnormal result.
  321.     '''
  322.     pass
  323.  
  324.  
  325. class Overflow(Inexact, Rounded):
  326.     '''Numerical overflow.
  327.  
  328.     This occurs and signals overflow if the adjusted exponent of a result
  329.     (from a conversion or from an operation that is not an attempt to divide
  330.     by zero), after rounding, would be greater than the largest value that
  331.     can be handled by the implementation (the value Emax).
  332.  
  333.     The result depends on the rounding mode:
  334.  
  335.     For round-half-up and round-half-even (and for round-half-down and
  336.     round-up, if implemented), the result of the operation is [sign,inf],
  337.     where sign is the sign of the intermediate result. For round-down, the
  338.     result is the largest finite number that can be represented in the
  339.     current precision, with the sign of the intermediate result. For
  340.     round-ceiling, the result is the same as for round-down if the sign of
  341.     the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
  342.     the result is the same as for round-down if the sign of the intermediate
  343.     result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
  344.     will also be raised.
  345.    '''
  346.     
  347.     def handle(self, context, sign, *args):
  348.         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_HALF_DOWN, ROUND_UP):
  349.             return Infsign[sign]
  350.         
  351.         if sign == 0:
  352.             if context.rounding == ROUND_CEILING:
  353.                 return Infsign[sign]
  354.             
  355.             return Decimal((sign, (9,) * context.prec, (context.Emax - context.prec) + 1))
  356.         
  357.         if sign == 1:
  358.             if context.rounding == ROUND_FLOOR:
  359.                 return Infsign[sign]
  360.             
  361.             return Decimal((sign, (9,) * context.prec, (context.Emax - context.prec) + 1))
  362.         
  363.  
  364.  
  365.  
  366. class Underflow(Inexact, Rounded, Subnormal):
  367.     '''Numerical underflow with result rounded to 0.
  368.  
  369.     This occurs and signals underflow if a result is inexact and the
  370.     adjusted exponent of the result would be smaller (more negative) than
  371.     the smallest value that can be handled by the implementation (the value
  372.     Emin). That is, the result is both inexact and subnormal.
  373.  
  374.     The result after an underflow will be a subnormal number rounded, if
  375.     necessary, so that its exponent is not less than Etiny. This may result
  376.     in 0 with the sign of the intermediate result and an exponent of Etiny.
  377.  
  378.     In all cases, Inexact, Rounded, and Subnormal will also be raised.
  379.     '''
  380.     pass
  381.  
  382. _signals = [
  383.     Clamped,
  384.     DivisionByZero,
  385.     Inexact,
  386.     Overflow,
  387.     Rounded,
  388.     Underflow,
  389.     InvalidOperation,
  390.     Subnormal]
  391. _condition_map = {
  392.     ConversionSyntax: InvalidOperation,
  393.     DivisionImpossible: InvalidOperation,
  394.     DivisionUndefined: InvalidOperation,
  395.     InvalidContext: InvalidOperation }
  396.  
  397. try:
  398.     import threading
  399. except ImportError:
  400.     import sys
  401.     
  402.     class MockThreading:
  403.         
  404.         def local(self, sys = sys):
  405.             return sys.modules[__name__]
  406.  
  407.  
  408.     threading = MockThreading()
  409.     del sys
  410.     del MockThreading
  411.  
  412.  
  413. try:
  414.     threading.local
  415. except AttributeError:
  416.     if hasattr(threading.currentThread(), '__decimal_context__'):
  417.         del threading.currentThread().__decimal_context__
  418.     
  419.     
  420.     def setcontext(context):
  421.         """Set this thread's context to context."""
  422.         if context in (DefaultContext, BasicContext, ExtendedContext):
  423.             context = context.copy()
  424.             context.clear_flags()
  425.         
  426.         threading.currentThread().__decimal_context__ = context
  427.  
  428.     
  429.     def getcontext():
  430.         """Returns this thread's context.
  431.  
  432.         If this thread does not yet have a context, returns
  433.         a new context and sets this thread's context.
  434.         New contexts are copies of DefaultContext.
  435.         """
  436.         
  437.         try:
  438.             return threading.currentThread().__decimal_context__
  439.         except AttributeError:
  440.             context = Context()
  441.             threading.currentThread().__decimal_context__ = context
  442.             return context
  443.  
  444.  
  445.  
  446. local = threading.local()
  447. if hasattr(local, '__decimal_context__'):
  448.     del local.__decimal_context__
  449.  
  450.  
  451. def getcontext(_local = local):
  452.     """Returns this thread's context.
  453.  
  454.         If this thread does not yet have a context, returns
  455.         a new context and sets this thread's context.
  456.         New contexts are copies of DefaultContext.
  457.         """
  458.     
  459.     try:
  460.         return _local.__decimal_context__
  461.     except AttributeError:
  462.         context = Context()
  463.         _local.__decimal_context__ = context
  464.         return context
  465.  
  466.  
  467.  
  468. def setcontext(context, _local = local):
  469.     """Set this thread's context to context."""
  470.     if context in (DefaultContext, BasicContext, ExtendedContext):
  471.         context = context.copy()
  472.         context.clear_flags()
  473.     
  474.     _local.__decimal_context__ = context
  475.  
  476. del threading
  477. del local
  478.  
  479. def localcontext(ctx = None):
  480.     '''Return a context manager for a copy of the supplied context
  481.  
  482.     Uses a copy of the current context if no context is specified
  483.     The returned context manager creates a local decimal context
  484.     in a with statement:
  485.         def sin(x):
  486.              with localcontext() as ctx:
  487.                  ctx.prec += 2
  488.                  # Rest of sin calculation algorithm
  489.                  # uses a precision 2 greater than normal
  490.              return +s # Convert result to normal precision
  491.  
  492.          def sin(x):
  493.              with localcontext(ExtendedContext):
  494.                  # Rest of sin calculation algorithm
  495.                  # uses the Extended Context from the
  496.                  # General Decimal Arithmetic Specification
  497.              return +s # Convert result to normal context
  498.  
  499.     '''
  500.     if ctx is None:
  501.         ctx = getcontext()
  502.     
  503.     return _ContextManager(ctx)
  504.  
  505.  
  506. class Decimal(object):
  507.     '''Floating point class for decimal arithmetic.'''
  508.     __slots__ = ('_exp', '_int', '_sign', '_is_special')
  509.     
  510.     def __new__(cls, value = '0', context = None):
  511.         '''Create a decimal point instance.
  512.  
  513.         >>> Decimal(\'3.14\')              # string input
  514.         Decimal("3.14")
  515.         >>> Decimal((0, (3, 1, 4), -2))  # tuple input (sign, digit_tuple, exponent)
  516.         Decimal("3.14")
  517.         >>> Decimal(314)                 # int or long
  518.         Decimal("314")
  519.         >>> Decimal(Decimal(314))        # another decimal instance
  520.         Decimal("314")
  521.         '''
  522.         self = object.__new__(cls)
  523.         self._is_special = False
  524.         if isinstance(value, _WorkRep):
  525.             self._sign = value.sign
  526.             self._int = tuple(map(int, str(value.int)))
  527.             self._exp = int(value.exp)
  528.             return self
  529.         
  530.         if isinstance(value, Decimal):
  531.             self._exp = value._exp
  532.             self._sign = value._sign
  533.             self._int = value._int
  534.             self._is_special = value._is_special
  535.             return self
  536.         
  537.         if isinstance(value, (int, long)):
  538.             if value >= 0:
  539.                 self._sign = 0
  540.             else:
  541.                 self._sign = 1
  542.             self._exp = 0
  543.             self._int = tuple(map(int, str(abs(value))))
  544.             return self
  545.         
  546.         if isinstance(value, (list, tuple)):
  547.             if len(value) != 3:
  548.                 raise ValueError, 'Invalid arguments'
  549.             
  550.             if value[0] not in (0, 1):
  551.                 raise ValueError, 'Invalid sign'
  552.             
  553.             for digit in value[1]:
  554.                 if not isinstance(digit, (int, long)) or digit < 0:
  555.                     raise ValueError, 'The second value in the tuple must be composed of non negative integer elements.'
  556.                     continue
  557.             
  558.             self._sign = value[0]
  559.             self._int = tuple(value[1])
  560.             if value[2] in ('F', 'n', 'N'):
  561.                 self._exp = value[2]
  562.                 self._is_special = True
  563.             else:
  564.                 self._exp = int(value[2])
  565.             return self
  566.         
  567.         if isinstance(value, float):
  568.             raise TypeError('Cannot convert float to Decimal.  ' + 'First convert the float to a string')
  569.         
  570.         if context is None:
  571.             context = getcontext()
  572.         
  573.         if isinstance(value, basestring):
  574.             if _isinfinity(value):
  575.                 self._exp = 'F'
  576.                 self._int = (0,)
  577.                 self._is_special = True
  578.                 if _isinfinity(value) == 1:
  579.                     self._sign = 0
  580.                 else:
  581.                     self._sign = 1
  582.                 return self
  583.             
  584.             if _isnan(value):
  585.                 (sig, sign, diag) = _isnan(value)
  586.                 self._is_special = True
  587.                 if len(diag) > context.prec:
  588.                     (self._sign, self._int, self._exp) = context._raise_error(ConversionSyntax)
  589.                     return self
  590.                 
  591.                 if sig == 1:
  592.                     self._exp = 'n'
  593.                 else:
  594.                     self._exp = 'N'
  595.                 self._sign = sign
  596.                 self._int = tuple(map(int, diag))
  597.                 return self
  598.             
  599.             
  600.             try:
  601.                 (self._sign, self._int, self._exp) = _string2exact(value)
  602.             except ValueError:
  603.                 self._is_special = True
  604.                 (self._sign, self._int, self._exp) = context._raise_error(ConversionSyntax)
  605.  
  606.             return self
  607.         
  608.         raise TypeError('Cannot convert %r to Decimal' % value)
  609.  
  610.     
  611.     def _isnan(self):
  612.         '''Returns whether the number is not actually one.
  613.  
  614.         0 if a number
  615.         1 if NaN
  616.         2 if sNaN
  617.         '''
  618.         if self._is_special:
  619.             exp = self._exp
  620.             if exp == 'n':
  621.                 return 1
  622.             elif exp == 'N':
  623.                 return 2
  624.             
  625.         
  626.         return 0
  627.  
  628.     
  629.     def _isinfinity(self):
  630.         '''Returns whether the number is infinite
  631.  
  632.         0 if finite or not a number
  633.         1 if +INF
  634.         -1 if -INF
  635.         '''
  636.         if self._exp == 'F':
  637.             if self._sign:
  638.                 return -1
  639.             
  640.             return 1
  641.         
  642.         return 0
  643.  
  644.     
  645.     def _check_nans(self, other = None, context = None):
  646.         '''Returns whether the number is not actually one.
  647.  
  648.         if self, other are sNaN, signal
  649.         if self, other are NaN return nan
  650.         return 0
  651.  
  652.         Done before operations.
  653.         '''
  654.         self_is_nan = self._isnan()
  655.         if other is None:
  656.             other_is_nan = False
  657.         else:
  658.             other_is_nan = other._isnan()
  659.         if self_is_nan or other_is_nan:
  660.             if context is None:
  661.                 context = getcontext()
  662.             
  663.             if self_is_nan == 2:
  664.                 return context._raise_error(InvalidOperation, 'sNaN', 1, self)
  665.             
  666.             if other_is_nan == 2:
  667.                 return context._raise_error(InvalidOperation, 'sNaN', 1, other)
  668.             
  669.             if self_is_nan:
  670.                 return self
  671.             
  672.             return other
  673.         
  674.         return 0
  675.  
  676.     
  677.     def __nonzero__(self):
  678.         '''Is the number non-zero?
  679.  
  680.         0 if self == 0
  681.         1 if self != 0
  682.         '''
  683.         if self._is_special:
  684.             return 1
  685.         
  686.         return sum(self._int) != 0
  687.  
  688.     
  689.     def __cmp__(self, other, context = None):
  690.         other = _convert_other(other)
  691.         if other is NotImplemented:
  692.             return other
  693.         
  694.         if self._is_special or other._is_special:
  695.             ans = self._check_nans(other, context)
  696.             if ans:
  697.                 return 1
  698.             
  699.             return cmp(self._isinfinity(), other._isinfinity())
  700.         
  701.         if not self and not other:
  702.             return 0
  703.         
  704.         if other._sign < self._sign:
  705.             return -1
  706.         
  707.         if self._sign < other._sign:
  708.             return 1
  709.         
  710.         self_adjusted = self.adjusted()
  711.         other_adjusted = other.adjusted()
  712.         if self_adjusted == other_adjusted and self._int + (0,) * (self._exp - other._exp) == other._int + (0,) * (other._exp - self._exp):
  713.             return 0
  714.         elif self_adjusted > other_adjusted and self._int[0] != 0:
  715.             return -1 ** self._sign
  716.         elif self_adjusted < other_adjusted and other._int[0] != 0:
  717.             return --1 ** self._sign
  718.         
  719.         if context is None:
  720.             context = getcontext()
  721.         
  722.         context = context._shallow_copy()
  723.         rounding = context._set_rounding(ROUND_UP)
  724.         flags = context._ignore_all_flags()
  725.         res = self.__sub__(other, context = context)
  726.         context._regard_flags(*flags)
  727.         context.rounding = rounding
  728.         if not res:
  729.             return 0
  730.         elif res._sign:
  731.             return -1
  732.         
  733.         return 1
  734.  
  735.     
  736.     def __eq__(self, other):
  737.         if not isinstance(other, (Decimal, int, long)):
  738.             return NotImplemented
  739.         
  740.         return self.__cmp__(other) == 0
  741.  
  742.     
  743.     def __ne__(self, other):
  744.         if not isinstance(other, (Decimal, int, long)):
  745.             return NotImplemented
  746.         
  747.         return self.__cmp__(other) != 0
  748.  
  749.     
  750.     def compare(self, other, context = None):
  751.         '''Compares one to another.
  752.  
  753.         -1 => a < b
  754.         0  => a = b
  755.         1  => a > b
  756.         NaN => one is NaN
  757.         Like __cmp__, but returns Decimal instances.
  758.         '''
  759.         other = _convert_other(other)
  760.         if other is NotImplemented:
  761.             return other
  762.         
  763.         if (self._is_special or other) and other._is_special:
  764.             ans = self._check_nans(other, context)
  765.             if ans:
  766.                 return ans
  767.             
  768.         
  769.         return Decimal(self.__cmp__(other, context))
  770.  
  771.     
  772.     def __hash__(self):
  773.         '''x.__hash__() <==> hash(x)'''
  774.         if self._is_special:
  775.             if self._isnan():
  776.                 raise TypeError('Cannot hash a NaN value.')
  777.             
  778.             return hash(str(self))
  779.         
  780.         i = int(self)
  781.         if self == Decimal(i):
  782.             return hash(i)
  783.         
  784.         if not self.__nonzero__():
  785.             raise AssertionError
  786.         return hash(str(self.normalize()))
  787.  
  788.     
  789.     def as_tuple(self):
  790.         '''Represents the number as a triple tuple.
  791.  
  792.         To show the internals exactly as they are.
  793.         '''
  794.         return (self._sign, self._int, self._exp)
  795.  
  796.     
  797.     def __repr__(self):
  798.         '''Represents the number as an instance of Decimal.'''
  799.         return 'Decimal("%s")' % str(self)
  800.  
  801.     
  802.     def __str__(self, eng = 0, context = None):
  803.         '''Return string representation of the number in scientific notation.
  804.  
  805.         Captures all of the information in the underlying representation.
  806.         '''
  807.         if self._is_special:
  808.             if self._isnan():
  809.                 minus = '-' * self._sign
  810.                 if self._int == (0,):
  811.                     info = ''
  812.                 else:
  813.                     info = ''.join(map(str, self._int))
  814.                 if self._isnan() == 2:
  815.                     return minus + 'sNaN' + info
  816.                 
  817.                 return minus + 'NaN' + info
  818.             
  819.             if self._isinfinity():
  820.                 minus = '-' * self._sign
  821.                 return minus + 'Infinity'
  822.             
  823.         
  824.         if context is None:
  825.             context = getcontext()
  826.         
  827.         tmp = map(str, self._int)
  828.         numdigits = len(self._int)
  829.         leftdigits = self._exp + numdigits
  830.         if eng and not self:
  831.             if self._exp < 0 and self._exp >= -6:
  832.                 s = '-' * self._sign + '0.' + '0' * abs(self._exp)
  833.                 return s
  834.             
  835.             exp = ((self._exp - 1) // 3 + 1) * 3
  836.             if exp != self._exp:
  837.                 s = '0.' + '0' * (exp - self._exp)
  838.             else:
  839.                 s = '0'
  840.             if exp != 0:
  841.                 if context.capitals:
  842.                     s += 'E'
  843.                 else:
  844.                     s += 'e'
  845.                 if exp > 0:
  846.                     s += '+'
  847.                 
  848.                 s += str(exp)
  849.             
  850.             s = '-' * self._sign + s
  851.             return s
  852.         
  853.         if eng:
  854.             dotplace = (leftdigits - 1) % 3 + 1
  855.             adjexp = leftdigits - 1 - (leftdigits - 1) % 3
  856.         else:
  857.             adjexp = leftdigits - 1
  858.             dotplace = 1
  859.         if self._exp == 0:
  860.             pass
  861.         elif self._exp < 0 and adjexp >= 0:
  862.             tmp.insert(leftdigits, '.')
  863.         elif self._exp < 0 and adjexp >= -6:
  864.             tmp[0:0] = [
  865.                 '0'] * int(-leftdigits)
  866.             tmp.insert(0, '0.')
  867.         elif numdigits > dotplace:
  868.             tmp.insert(dotplace, '.')
  869.         elif numdigits < dotplace:
  870.             tmp.extend([
  871.                 '0'] * (dotplace - numdigits))
  872.         
  873.         if adjexp:
  874.             if not context.capitals:
  875.                 tmp.append('e')
  876.             else:
  877.                 tmp.append('E')
  878.                 if adjexp > 0:
  879.                     tmp.append('+')
  880.                 
  881.             tmp.append(str(adjexp))
  882.         
  883.         if eng:
  884.             while tmp[0:1] == [
  885.                 '0']:
  886.                 tmp[0:1] = []
  887.             if len(tmp) == 0 and tmp[0] == '.' or tmp[0].lower() == 'e':
  888.                 tmp[0:0] = [
  889.                     '0']
  890.             
  891.         
  892.         if self._sign:
  893.             tmp.insert(0, '-')
  894.         
  895.         return ''.join(tmp)
  896.  
  897.     
  898.     def to_eng_string(self, context = None):
  899.         '''Convert to engineering-type string.
  900.  
  901.         Engineering notation has an exponent which is a multiple of 3, so there
  902.         are up to 3 digits left of the decimal place.
  903.  
  904.         Same rules for when in exponential and when as a value as in __str__.
  905.         '''
  906.         return self.__str__(eng = 1, context = context)
  907.  
  908.     
  909.     def __neg__(self, context = None):
  910.         '''Returns a copy with the sign switched.
  911.  
  912.         Rounds, if it has reason.
  913.         '''
  914.         if self._is_special:
  915.             ans = self._check_nans(context = context)
  916.             if ans:
  917.                 return ans
  918.             
  919.         
  920.         if not self:
  921.             sign = 0
  922.         elif self._sign:
  923.             sign = 0
  924.         else:
  925.             sign = 1
  926.         if context is None:
  927.             context = getcontext()
  928.         
  929.         if context._rounding_decision == ALWAYS_ROUND:
  930.             return Decimal((sign, self._int, self._exp))._fix(context)
  931.         
  932.         return Decimal((sign, self._int, self._exp))
  933.  
  934.     
  935.     def __pos__(self, context = None):
  936.         '''Returns a copy, unless it is a sNaN.
  937.  
  938.         Rounds the number (if more then precision digits)
  939.         '''
  940.         if self._is_special:
  941.             ans = self._check_nans(context = context)
  942.             if ans:
  943.                 return ans
  944.             
  945.         
  946.         sign = self._sign
  947.         if not self:
  948.             sign = 0
  949.         
  950.         if context is None:
  951.             context = getcontext()
  952.         
  953.         if context._rounding_decision == ALWAYS_ROUND:
  954.             ans = self._fix(context)
  955.         else:
  956.             ans = Decimal(self)
  957.         ans._sign = sign
  958.         return ans
  959.  
  960.     
  961.     def __abs__(self, round = 1, context = None):
  962.         '''Returns the absolute value of self.
  963.  
  964.         If the second argument is 0, do not round.
  965.         '''
  966.         if self._is_special:
  967.             ans = self._check_nans(context = context)
  968.             if ans:
  969.                 return ans
  970.             
  971.         
  972.         if not round:
  973.             if context is None:
  974.                 context = getcontext()
  975.             
  976.             context = context._shallow_copy()
  977.             context._set_rounding_decision(NEVER_ROUND)
  978.         
  979.         if self._sign:
  980.             ans = self.__neg__(context = context)
  981.         else:
  982.             ans = self.__pos__(context = context)
  983.         return ans
  984.  
  985.     
  986.     def __add__(self, other, context = None):
  987.         '''Returns self + other.
  988.  
  989.         -INF + INF (or the reverse) cause InvalidOperation errors.
  990.         '''
  991.         other = _convert_other(other)
  992.         if other is NotImplemented:
  993.             return other
  994.         
  995.         if context is None:
  996.             context = getcontext()
  997.         
  998.         if self._is_special or other._is_special:
  999.             ans = self._check_nans(other, context)
  1000.             if ans:
  1001.                 return ans
  1002.             
  1003.             if self._isinfinity():
  1004.                 if self._sign != other._sign and other._isinfinity():
  1005.                     return context._raise_error(InvalidOperation, '-INF + INF')
  1006.                 
  1007.                 return Decimal(self)
  1008.             
  1009.             if other._isinfinity():
  1010.                 return Decimal(other)
  1011.             
  1012.         
  1013.         shouldround = context._rounding_decision == ALWAYS_ROUND
  1014.         exp = min(self._exp, other._exp)
  1015.         negativezero = 0
  1016.         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
  1017.             negativezero = 1
  1018.         
  1019.         if not self and not other:
  1020.             sign = min(self._sign, other._sign)
  1021.             if negativezero:
  1022.                 sign = 1
  1023.             
  1024.             return Decimal((sign, (0,), exp))
  1025.         
  1026.         if not self:
  1027.             exp = max(exp, other._exp - context.prec - 1)
  1028.             ans = other._rescale(exp, watchexp = 0, context = context)
  1029.             if shouldround:
  1030.                 ans = ans._fix(context)
  1031.             
  1032.             return ans
  1033.         
  1034.         if not other:
  1035.             exp = max(exp, self._exp - context.prec - 1)
  1036.             ans = self._rescale(exp, watchexp = 0, context = context)
  1037.             if shouldround:
  1038.                 ans = ans._fix(context)
  1039.             
  1040.             return ans
  1041.         
  1042.         op1 = _WorkRep(self)
  1043.         op2 = _WorkRep(other)
  1044.         (op1, op2) = _normalize(op1, op2, shouldround, context.prec)
  1045.         result = _WorkRep()
  1046.         if op1.sign != op2.sign:
  1047.             if op1.int == op2.int:
  1048.                 if exp < context.Etiny():
  1049.                     exp = context.Etiny()
  1050.                     context._raise_error(Clamped)
  1051.                 
  1052.                 return Decimal((negativezero, (0,), exp))
  1053.             
  1054.             if op1.int < op2.int:
  1055.                 op1 = op2
  1056.                 op2 = op1
  1057.             
  1058.             if op1.sign == 1:
  1059.                 result.sign = 1
  1060.                 op1.sign = op2.sign
  1061.                 op2.sign = op1.sign
  1062.             else:
  1063.                 result.sign = 0
  1064.         elif op1.sign == 1:
  1065.             result.sign = 1
  1066.             (op1.sign, op2.sign) = (0, 0)
  1067.         else:
  1068.             result.sign = 0
  1069.         if op2.sign == 0:
  1070.             result.int = op1.int + op2.int
  1071.         else:
  1072.             result.int = op1.int - op2.int
  1073.         result.exp = op1.exp
  1074.         ans = Decimal(result)
  1075.         if shouldround:
  1076.             ans = ans._fix(context)
  1077.         
  1078.         return ans
  1079.  
  1080.     __radd__ = __add__
  1081.     
  1082.     def __sub__(self, other, context = None):
  1083.         '''Return self + (-other)'''
  1084.         other = _convert_other(other)
  1085.         if other is NotImplemented:
  1086.             return other
  1087.         
  1088.         if self._is_special or other._is_special:
  1089.             ans = self._check_nans(other, context = context)
  1090.             if ans:
  1091.                 return ans
  1092.             
  1093.         
  1094.         tmp = Decimal(other)
  1095.         tmp._sign = 1 - tmp._sign
  1096.         return self.__add__(tmp, context = context)
  1097.  
  1098.     
  1099.     def __rsub__(self, other, context = None):
  1100.         '''Return other + (-self)'''
  1101.         other = _convert_other(other)
  1102.         if other is NotImplemented:
  1103.             return other
  1104.         
  1105.         tmp = Decimal(self)
  1106.         tmp._sign = 1 - tmp._sign
  1107.         return other.__add__(tmp, context = context)
  1108.  
  1109.     
  1110.     def _increment(self, round = 1, context = None):
  1111.         """Special case of add, adding 1eExponent
  1112.  
  1113.         Since it is common, (rounding, for example) this adds
  1114.         (sign)*one E self._exp to the number more efficiently than add.
  1115.  
  1116.         For example:
  1117.         Decimal('5.624e10')._increment() == Decimal('5.625e10')
  1118.         """
  1119.         if self._is_special:
  1120.             ans = self._check_nans(context = context)
  1121.             if ans:
  1122.                 return ans
  1123.             
  1124.             return Decimal(self)
  1125.         
  1126.         L = list(self._int)
  1127.         L[-1] += 1
  1128.         spot = len(L) - 1
  1129.         while L[spot] == 10:
  1130.             L[spot] = 0
  1131.             if spot == 0:
  1132.                 L[0:0] = [
  1133.                     1]
  1134.                 break
  1135.             
  1136.             L[spot - 1] += 1
  1137.             spot -= 1
  1138.         ans = Decimal((self._sign, L, self._exp))
  1139.         if context is None:
  1140.             context = getcontext()
  1141.         
  1142.         if round and context._rounding_decision == ALWAYS_ROUND:
  1143.             ans = ans._fix(context)
  1144.         
  1145.         return ans
  1146.  
  1147.     
  1148.     def __mul__(self, other, context = None):
  1149.         '''Return self * other.
  1150.  
  1151.         (+-) INF * 0 (or its reverse) raise InvalidOperation.
  1152.         '''
  1153.         other = _convert_other(other)
  1154.         if other is NotImplemented:
  1155.             return other
  1156.         
  1157.         if context is None:
  1158.             context = getcontext()
  1159.         
  1160.         resultsign = self._sign ^ other._sign
  1161.         if self._is_special or other._is_special:
  1162.             ans = self._check_nans(other, context)
  1163.             if ans:
  1164.                 return ans
  1165.             
  1166.             if self._isinfinity():
  1167.                 if not other:
  1168.                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
  1169.                 
  1170.                 return Infsign[resultsign]
  1171.             
  1172.             if other._isinfinity():
  1173.                 if not self:
  1174.                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
  1175.                 
  1176.                 return Infsign[resultsign]
  1177.             
  1178.         
  1179.         resultexp = self._exp + other._exp
  1180.         shouldround = context._rounding_decision == ALWAYS_ROUND
  1181.         if not self or not other:
  1182.             ans = Decimal((resultsign, (0,), resultexp))
  1183.             if shouldround:
  1184.                 ans = ans._fix(context)
  1185.             
  1186.             return ans
  1187.         
  1188.         if self._int == (1,):
  1189.             ans = Decimal((resultsign, other._int, resultexp))
  1190.             if shouldround:
  1191.                 ans = ans._fix(context)
  1192.             
  1193.             return ans
  1194.         
  1195.         if other._int == (1,):
  1196.             ans = Decimal((resultsign, self._int, resultexp))
  1197.             if shouldround:
  1198.                 ans = ans._fix(context)
  1199.             
  1200.             return ans
  1201.         
  1202.         op1 = _WorkRep(self)
  1203.         op2 = _WorkRep(other)
  1204.         ans = Decimal((resultsign, map(int, str(op1.int * op2.int)), resultexp))
  1205.         if shouldround:
  1206.             ans = ans._fix(context)
  1207.         
  1208.         return ans
  1209.  
  1210.     __rmul__ = __mul__
  1211.     
  1212.     def __div__(self, other, context = None):
  1213.         '''Return self / other.'''
  1214.         return self._divide(other, context = context)
  1215.  
  1216.     __truediv__ = __div__
  1217.     
  1218.     def _divide(self, other, divmod = 0, context = None):
  1219.         '''Return a / b, to context.prec precision.
  1220.  
  1221.         divmod:
  1222.         0 => true division
  1223.         1 => (a //b, a%b)
  1224.         2 => a //b
  1225.         3 => a%b
  1226.  
  1227.         Actually, if divmod is 2 or 3 a tuple is returned, but errors for
  1228.         computing the other value are not raised.
  1229.         '''
  1230.         other = _convert_other(other)
  1231.         if other is NotImplemented:
  1232.             if divmod in (0, 1):
  1233.                 return NotImplemented
  1234.             
  1235.             return (NotImplemented, NotImplemented)
  1236.         
  1237.         if context is None:
  1238.             context = getcontext()
  1239.         
  1240.         sign = self._sign ^ other._sign
  1241.         if self._is_special or other._is_special:
  1242.             ans = self._check_nans(other, context)
  1243.             if ans:
  1244.                 if divmod:
  1245.                     return (ans, ans)
  1246.                 
  1247.                 return ans
  1248.             
  1249.             if self._isinfinity() and other._isinfinity():
  1250.                 if divmod:
  1251.                     return (context._raise_error(InvalidOperation, '(+-)INF // (+-)INF'), context._raise_error(InvalidOperation, '(+-)INF % (+-)INF'))
  1252.                 
  1253.                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
  1254.             
  1255.             if self._isinfinity():
  1256.                 if divmod == 1:
  1257.                     return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x'))
  1258.                 elif divmod == 2:
  1259.                     return (Infsign[sign], NaN)
  1260.                 elif divmod == 3:
  1261.                     return (Infsign[sign], context._raise_error(InvalidOperation, 'INF % x'))
  1262.                 
  1263.                 return Infsign[sign]
  1264.             
  1265.             if other._isinfinity():
  1266.                 if divmod:
  1267.                     return (Decimal((sign, (0,), 0)), Decimal(self))
  1268.                 
  1269.                 context._raise_error(Clamped, 'Division by infinity')
  1270.                 return Decimal((sign, (0,), context.Etiny()))
  1271.             
  1272.         
  1273.         if not self and not other:
  1274.             if divmod:
  1275.                 return context._raise_error(DivisionUndefined, '0 / 0', 1)
  1276.             
  1277.             return context._raise_error(DivisionUndefined, '0 / 0')
  1278.         
  1279.         if not self:
  1280.             if divmod:
  1281.                 otherside = Decimal(self)
  1282.                 otherside._exp = min(self._exp, other._exp)
  1283.                 return (Decimal((sign, (0,), 0)), otherside)
  1284.             
  1285.             exp = self._exp - other._exp
  1286.             if exp < context.Etiny():
  1287.                 exp = context.Etiny()
  1288.                 context._raise_error(Clamped, '0e-x / y')
  1289.             
  1290.             if exp > context.Emax:
  1291.                 exp = context.Emax
  1292.                 context._raise_error(Clamped, '0e+x / y')
  1293.             
  1294.             return Decimal((sign, (0,), exp))
  1295.         
  1296.         if not other:
  1297.             if divmod:
  1298.                 return context._raise_error(DivisionByZero, 'divmod(x,0)', sign, 1)
  1299.             
  1300.             return context._raise_error(DivisionByZero, 'x / 0', sign)
  1301.         
  1302.         shouldround = context._rounding_decision == ALWAYS_ROUND
  1303.         if divmod and self.__abs__(0, context) < other.__abs__(0, context):
  1304.             if divmod == 1 or divmod == 3:
  1305.                 exp = min(self._exp, other._exp)
  1306.                 ans2 = self._rescale(exp, context = context, watchexp = 0)
  1307.                 if shouldround:
  1308.                     ans2 = ans2._fix(context)
  1309.                 
  1310.                 return (Decimal((sign, (0,), 0)), ans2)
  1311.             elif divmod == 2:
  1312.                 return (Decimal((sign, (0,), 0)), Decimal(self))
  1313.             
  1314.         
  1315.         op1 = _WorkRep(self)
  1316.         op2 = _WorkRep(other)
  1317.         (op1, op2, adjust) = _adjust_coefficients(op1, op2)
  1318.         res = _WorkRep((sign, 0, op1.exp - op2.exp))
  1319.         if divmod and res.exp > context.prec + 1:
  1320.             return context._raise_error(DivisionImpossible)
  1321.         
  1322.         prec_limit = 10 ** context.prec
  1323.         while None:
  1324.             while op2.int <= op1.int:
  1325.                 res.int += 1
  1326.                 op1.int -= op2.int
  1327.                 continue
  1328.                 op1
  1329.             if op1.int == 0 and adjust >= 0 and not divmod:
  1330.                 break
  1331.             
  1332.             if res.int >= prec_limit and shouldround:
  1333.                 if divmod:
  1334.                     return context._raise_error(DivisionImpossible)
  1335.                 
  1336.                 shouldround = 1
  1337.                 break
  1338.             
  1339.             res.int *= 10
  1340.             res.exp -= 1
  1341.             adjust += 1
  1342.             op1.int *= 10
  1343.             op1.exp -= 1
  1344.             if res.exp == 0 and divmod and op2.int > op1.int:
  1345.                 otherside = Decimal(op1)
  1346.                 frozen = context._ignore_all_flags()
  1347.                 exp = min(self._exp, other._exp)
  1348.                 otherside = otherside._rescale(exp, context = context)
  1349.                 context._regard_flags(*frozen)
  1350.                 return (Decimal(res), otherside)
  1351.                 continue
  1352.             continue
  1353.             ans = Decimal(res)
  1354.             if shouldround:
  1355.                 ans = ans._fix(context)
  1356.             
  1357.         return ans
  1358.  
  1359.     
  1360.     def __rdiv__(self, other, context = None):
  1361.         '''Swaps self/other and returns __div__.'''
  1362.         other = _convert_other(other)
  1363.         if other is NotImplemented:
  1364.             return other
  1365.         
  1366.         return other.__div__(self, context = context)
  1367.  
  1368.     __rtruediv__ = __rdiv__
  1369.     
  1370.     def __divmod__(self, other, context = None):
  1371.         '''
  1372.         (self // other, self % other)
  1373.         '''
  1374.         return self._divide(other, 1, context)
  1375.  
  1376.     
  1377.     def __rdivmod__(self, other, context = None):
  1378.         '''Swaps self/other and returns __divmod__.'''
  1379.         other = _convert_other(other)
  1380.         if other is NotImplemented:
  1381.             return other
  1382.         
  1383.         return other.__divmod__(self, context = context)
  1384.  
  1385.     
  1386.     def __mod__(self, other, context = None):
  1387.         '''
  1388.         self % other
  1389.         '''
  1390.         other = _convert_other(other)
  1391.         if other is NotImplemented:
  1392.             return other
  1393.         
  1394.         if self._is_special or other._is_special:
  1395.             ans = self._check_nans(other, context)
  1396.             if ans:
  1397.                 return ans
  1398.             
  1399.         
  1400.         if self and not other:
  1401.             return context._raise_error(InvalidOperation, 'x % 0')
  1402.         
  1403.         return self._divide(other, 3, context)[1]
  1404.  
  1405.     
  1406.     def __rmod__(self, other, context = None):
  1407.         '''Swaps self/other and returns __mod__.'''
  1408.         other = _convert_other(other)
  1409.         if other is NotImplemented:
  1410.             return other
  1411.         
  1412.         return other.__mod__(self, context = context)
  1413.  
  1414.     
  1415.     def remainder_near(self, other, context = None):
  1416.         '''
  1417.         Remainder nearest to 0-  abs(remainder-near) <= other/2
  1418.         '''
  1419.         other = _convert_other(other)
  1420.         if other is NotImplemented:
  1421.             return other
  1422.         
  1423.         if self._is_special or other._is_special:
  1424.             ans = self._check_nans(other, context)
  1425.             if ans:
  1426.                 return ans
  1427.             
  1428.         
  1429.         if self and not other:
  1430.             return context._raise_error(InvalidOperation, 'x % 0')
  1431.         
  1432.         if context is None:
  1433.             context = getcontext()
  1434.         
  1435.         context = context._shallow_copy()
  1436.         flags = context._ignore_flags(Rounded, Inexact)
  1437.         (side, r) = self.__divmod__(other, context = context)
  1438.         if r._isnan():
  1439.             context._regard_flags(*flags)
  1440.             return r
  1441.         
  1442.         context = context._shallow_copy()
  1443.         rounding = context._set_rounding_decision(NEVER_ROUND)
  1444.         if other._sign:
  1445.             comparison = other.__div__(Decimal(-2), context = context)
  1446.         else:
  1447.             comparison = other.__div__(Decimal(2), context = context)
  1448.         context._set_rounding_decision(rounding)
  1449.         context._regard_flags(*flags)
  1450.         s1 = r._sign
  1451.         s2 = comparison._sign
  1452.         (r._sign, comparison._sign) = (0, 0)
  1453.         if r < comparison:
  1454.             r._sign = s1
  1455.             comparison._sign = s2
  1456.             self.__divmod__(other, context = context)
  1457.             return r._fix(context)
  1458.         
  1459.         r._sign = s1
  1460.         comparison._sign = s2
  1461.         rounding = context._set_rounding_decision(NEVER_ROUND)
  1462.         (side, r) = self.__divmod__(other, context = context)
  1463.         context._set_rounding_decision(rounding)
  1464.         if r._isnan():
  1465.             return r
  1466.         
  1467.         decrease = not side._iseven()
  1468.         rounding = context._set_rounding_decision(NEVER_ROUND)
  1469.         side = side.__abs__(context = context)
  1470.         context._set_rounding_decision(rounding)
  1471.         s1 = r._sign
  1472.         s2 = comparison._sign
  1473.         (r._sign, comparison._sign) = (0, 0)
  1474.         return r._fix(context)
  1475.  
  1476.     
  1477.     def __floordiv__(self, other, context = None):
  1478.         '''self // other'''
  1479.         return self._divide(other, 2, context)[0]
  1480.  
  1481.     
  1482.     def __rfloordiv__(self, other, context = None):
  1483.         '''Swaps self/other and returns __floordiv__.'''
  1484.         other = _convert_other(other)
  1485.         if other is NotImplemented:
  1486.             return other
  1487.         
  1488.         return other.__floordiv__(self, context = context)
  1489.  
  1490.     
  1491.     def __float__(self):
  1492.         '''Float representation.'''
  1493.         return float(str(self))
  1494.  
  1495.     
  1496.     def __int__(self):
  1497.         '''Converts self to an int, truncating if necessary.'''
  1498.         if self._is_special:
  1499.             if self._isnan():
  1500.                 context = getcontext()
  1501.                 return context._raise_error(InvalidContext)
  1502.             elif self._isinfinity():
  1503.                 raise OverflowError, 'Cannot convert infinity to long'
  1504.             
  1505.         
  1506.         if self._exp >= 0:
  1507.             s = ''.join(map(str, self._int)) + '0' * self._exp
  1508.         else:
  1509.             s = ''.join(map(str, self._int))[:self._exp]
  1510.         if s == '':
  1511.             s = '0'
  1512.         
  1513.         sign = '-' * self._sign
  1514.         return int(sign + s)
  1515.  
  1516.     
  1517.     def __long__(self):
  1518.         '''Converts to a long.
  1519.  
  1520.         Equivalent to long(int(self))
  1521.         '''
  1522.         return long(self.__int__())
  1523.  
  1524.     
  1525.     def _fix(self, context):
  1526.         '''Round if it is necessary to keep self within prec precision.
  1527.  
  1528.         Rounds and fixes the exponent.  Does not raise on a sNaN.
  1529.  
  1530.         Arguments:
  1531.         self - Decimal instance
  1532.         context - context used.
  1533.         '''
  1534.         if self._is_special:
  1535.             return self
  1536.         
  1537.         if context is None:
  1538.             context = getcontext()
  1539.         
  1540.         prec = context.prec
  1541.         ans = self._fixexponents(context)
  1542.         if len(ans._int) > prec:
  1543.             ans = ans._round(prec, context = context)
  1544.             ans = ans._fixexponents(context)
  1545.         
  1546.         return ans
  1547.  
  1548.     
  1549.     def _fixexponents(self, context):
  1550.         '''Fix the exponents and return a copy with the exponent in bounds.
  1551.         Only call if known to not be a special value.
  1552.         '''
  1553.         folddown = context._clamp
  1554.         Emin = context.Emin
  1555.         ans = self
  1556.         ans_adjusted = ans.adjusted()
  1557.         if ans_adjusted < Emin:
  1558.             Etiny = context.Etiny()
  1559.             if ans._exp < Etiny:
  1560.                 if not ans:
  1561.                     ans = Decimal(self)
  1562.                     ans._exp = Etiny
  1563.                     context._raise_error(Clamped)
  1564.                     return ans
  1565.                 
  1566.                 ans = ans._rescale(Etiny, context = context)
  1567.                 context._raise_error(Subnormal)
  1568.                 if context.flags[Inexact]:
  1569.                     context._raise_error(Underflow)
  1570.                 
  1571.             elif ans:
  1572.                 context._raise_error(Subnormal)
  1573.             
  1574.         else:
  1575.             Etop = context.Etop()
  1576.             if folddown and ans._exp > Etop:
  1577.                 context._raise_error(Clamped)
  1578.                 ans = ans._rescale(Etop, context = context)
  1579.             else:
  1580.                 Emax = context.Emax
  1581.                 if ans_adjusted > Emax:
  1582.                     if not ans:
  1583.                         ans = Decimal(self)
  1584.                         ans._exp = Emax
  1585.                         context._raise_error(Clamped)
  1586.                         return ans
  1587.                     
  1588.                     context._raise_error(Inexact)
  1589.                     context._raise_error(Rounded)
  1590.                     return context._raise_error(Overflow, 'above Emax', ans._sign)
  1591.                 
  1592.         return ans
  1593.  
  1594.     
  1595.     def _round(self, prec = None, rounding = None, context = None):
  1596.         '''Returns a rounded version of self.
  1597.  
  1598.         You can specify the precision or rounding method.  Otherwise, the
  1599.         context determines it.
  1600.         '''
  1601.         if self._is_special:
  1602.             ans = self._check_nans(context = context)
  1603.             if ans:
  1604.                 return ans
  1605.             
  1606.             if self._isinfinity():
  1607.                 return Decimal(self)
  1608.             
  1609.         
  1610.         if context is None:
  1611.             context = getcontext()
  1612.         
  1613.         if rounding is None:
  1614.             rounding = context.rounding
  1615.         
  1616.         if prec is None:
  1617.             prec = context.prec
  1618.         
  1619.         if not self:
  1620.             if prec <= 0:
  1621.                 dig = (0,)
  1622.                 exp = (len(self._int) - prec) + self._exp
  1623.             else:
  1624.                 dig = (0,) * prec
  1625.                 exp = len(self._int) + self._exp - prec
  1626.             ans = Decimal((self._sign, dig, exp))
  1627.             context._raise_error(Rounded)
  1628.             return ans
  1629.         
  1630.         if prec == 0:
  1631.             temp = Decimal(self)
  1632.             temp._int = (0,) + temp._int
  1633.             prec = 1
  1634.         elif prec < 0:
  1635.             exp = self._exp + len(self._int) - prec - 1
  1636.             temp = Decimal((self._sign, (0, 1), exp))
  1637.             prec = 1
  1638.         else:
  1639.             temp = Decimal(self)
  1640.         numdigits = len(temp._int)
  1641.         if prec == numdigits:
  1642.             return temp
  1643.         
  1644.         expdiff = prec - numdigits
  1645.         if expdiff > 0:
  1646.             tmp = list(temp._int)
  1647.             tmp.extend([
  1648.                 0] * expdiff)
  1649.             ans = Decimal((temp._sign, tmp, temp._exp - expdiff))
  1650.             return ans
  1651.         
  1652.         lostdigits = self._int[expdiff:]
  1653.         if lostdigits == (0,) * len(lostdigits):
  1654.             ans = Decimal((temp._sign, temp._int[:prec], temp._exp - expdiff))
  1655.             context._raise_error(Rounded)
  1656.             return ans
  1657.         
  1658.         this_function = getattr(temp, self._pick_rounding_function[rounding])
  1659.         if prec != context.prec:
  1660.             context = context._shallow_copy()
  1661.             context.prec = prec
  1662.         
  1663.         ans = this_function(prec, expdiff, context)
  1664.         context._raise_error(Rounded)
  1665.         context._raise_error(Inexact, 'Changed in rounding')
  1666.         return ans
  1667.  
  1668.     _pick_rounding_function = { }
  1669.     
  1670.     def _round_down(self, prec, expdiff, context):
  1671.         '''Also known as round-towards-0, truncate.'''
  1672.         return Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  1673.  
  1674.     
  1675.     def _round_half_up(self, prec, expdiff, context, tmp = None):
  1676.         '''Rounds 5 up (away from 0)'''
  1677.         if tmp is None:
  1678.             tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  1679.         
  1680.         if self._int[prec] >= 5:
  1681.             tmp = tmp._increment(round = 0, context = context)
  1682.             if len(tmp._int) > prec:
  1683.                 return Decimal((tmp._sign, tmp._int[:-1], tmp._exp + 1))
  1684.             
  1685.         
  1686.         return tmp
  1687.  
  1688.     
  1689.     def _round_half_even(self, prec, expdiff, context):
  1690.         '''Round 5 to even, rest to nearest.'''
  1691.         tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  1692.         half = self._int[prec] == 5
  1693.         if half:
  1694.             for digit in self._int[prec + 1:]:
  1695.                 if digit != 0:
  1696.                     half = 0
  1697.                     break
  1698.                     continue
  1699.             
  1700.         
  1701.         if half:
  1702.             if self._int[prec - 1] & 1 == 0:
  1703.                 return tmp
  1704.             
  1705.         
  1706.         return self._round_half_up(prec, expdiff, context, tmp)
  1707.  
  1708.     
  1709.     def _round_half_down(self, prec, expdiff, context):
  1710.         '''Round 5 down'''
  1711.         tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  1712.         half = self._int[prec] == 5
  1713.         if half:
  1714.             for digit in self._int[prec + 1:]:
  1715.                 if digit != 0:
  1716.                     half = 0
  1717.                     break
  1718.                     continue
  1719.             
  1720.         
  1721.         if half:
  1722.             return tmp
  1723.         
  1724.         return self._round_half_up(prec, expdiff, context, tmp)
  1725.  
  1726.     
  1727.     def _round_up(self, prec, expdiff, context):
  1728.         '''Rounds away from 0.'''
  1729.         tmp = Decimal((self._sign, self._int[:prec], self._exp - expdiff))
  1730.         for digit in self._int[prec:]:
  1731.             if digit != 0:
  1732.                 tmp = tmp._increment(round = 1, context = context)
  1733.                 if len(tmp._int) > prec:
  1734.                     return Decimal((tmp._sign, tmp._int[:-1], tmp._exp + 1))
  1735.                 else:
  1736.                     return tmp
  1737.             len(tmp._int) > prec
  1738.         
  1739.         return tmp
  1740.  
  1741.     
  1742.     def _round_ceiling(self, prec, expdiff, context):
  1743.         '''Rounds up (not away from 0 if negative.)'''
  1744.         if self._sign:
  1745.             return self._round_down(prec, expdiff, context)
  1746.         else:
  1747.             return self._round_up(prec, expdiff, context)
  1748.  
  1749.     
  1750.     def _round_floor(self, prec, expdiff, context):
  1751.         '''Rounds down (not towards 0 if negative)'''
  1752.         if not self._sign:
  1753.             return self._round_down(prec, expdiff, context)
  1754.         else:
  1755.             return self._round_up(prec, expdiff, context)
  1756.  
  1757.     
  1758.     def __pow__(self, n, modulo = None, context = None):
  1759.         """Return self ** n (mod modulo)
  1760.  
  1761.         If modulo is None (default), don't take it mod modulo.
  1762.         """
  1763.         n = _convert_other(n)
  1764.         if n is NotImplemented:
  1765.             return n
  1766.         
  1767.         if context is None:
  1768.             context = getcontext()
  1769.         
  1770.         if self._is_special and n._is_special or n.adjusted() > 8:
  1771.             if n._isinfinity() or n.adjusted() > 8:
  1772.                 return context._raise_error(InvalidOperation, 'x ** INF')
  1773.             
  1774.             ans = self._check_nans(n, context)
  1775.             if ans:
  1776.                 return ans
  1777.             
  1778.         
  1779.         if not n._isinteger():
  1780.             return context._raise_error(InvalidOperation, 'x ** (non-integer)')
  1781.         
  1782.         if not self and not n:
  1783.             return context._raise_error(InvalidOperation, '0 ** 0')
  1784.         
  1785.         if not n:
  1786.             return Decimal(1)
  1787.         
  1788.         if self == Decimal(1):
  1789.             return Decimal(1)
  1790.         
  1791.         if self._sign:
  1792.             pass
  1793.         sign = not n._iseven()
  1794.         n = int(n)
  1795.         if self._isinfinity():
  1796.             if modulo:
  1797.                 return context._raise_error(InvalidOperation, 'INF % x')
  1798.             
  1799.             if n > 0:
  1800.                 return Infsign[sign]
  1801.             
  1802.             return Decimal((sign, (0,), 0))
  1803.         
  1804.         if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax and self:
  1805.             tmp = Decimal('inf')
  1806.             tmp._sign = sign
  1807.             context._raise_error(Rounded)
  1808.             context._raise_error(Inexact)
  1809.             context._raise_error(Overflow, 'Big power', sign)
  1810.             return tmp
  1811.         
  1812.         elength = len(str(abs(n)))
  1813.         firstprec = context.prec
  1814.         if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
  1815.             return context._raise_error(Overflow, 'Too much precision.', sign)
  1816.         
  1817.         mul = Decimal(self)
  1818.         val = Decimal(1)
  1819.         context = context._shallow_copy()
  1820.         context.prec = firstprec + elength + 1
  1821.         if n < 0:
  1822.             n = -n
  1823.             mul = Decimal(1).__div__(mul, context = context)
  1824.         
  1825.         spot = 1
  1826.         while spot <= n:
  1827.             spot <<= 1
  1828.         spot >>= 1
  1829.         while spot:
  1830.             val = val.__mul__(val, context = context)
  1831.             if val._isinfinity():
  1832.                 val = Infsign[sign]
  1833.                 break
  1834.             
  1835.             if spot & n:
  1836.                 val = val.__mul__(mul, context = context)
  1837.             
  1838.             if modulo is not None:
  1839.                 val = val.__mod__(modulo, context = context)
  1840.             
  1841.             spot >>= 1
  1842.         context.prec = firstprec
  1843.         if context._rounding_decision == ALWAYS_ROUND:
  1844.             return val._fix(context)
  1845.         
  1846.         return val
  1847.  
  1848.     
  1849.     def __rpow__(self, other, context = None):
  1850.         '''Swaps self/other and returns __pow__.'''
  1851.         other = _convert_other(other)
  1852.         if other is NotImplemented:
  1853.             return other
  1854.         
  1855.         return other.__pow__(self, context = context)
  1856.  
  1857.     
  1858.     def normalize(self, context = None):
  1859.         '''Normalize- strip trailing 0s, change anything equal to 0 to 0e0'''
  1860.         if self._is_special:
  1861.             ans = self._check_nans(context = context)
  1862.             if ans:
  1863.                 return ans
  1864.             
  1865.         
  1866.         dup = self._fix(context)
  1867.         if dup._isinfinity():
  1868.             return dup
  1869.         
  1870.         if not dup:
  1871.             return Decimal((dup._sign, (0,), 0))
  1872.         
  1873.         end = len(dup._int)
  1874.         exp = dup._exp
  1875.         while dup._int[end - 1] == 0:
  1876.             exp += 1
  1877.             end -= 1
  1878.         return Decimal((dup._sign, dup._int[:end], exp))
  1879.  
  1880.     
  1881.     def quantize(self, exp, rounding = None, context = None, watchexp = 1):
  1882.         '''Quantize self so its exponent is the same as that of exp.
  1883.  
  1884.         Similar to self._rescale(exp._exp) but with error checking.
  1885.         '''
  1886.         if self._is_special or exp._is_special:
  1887.             ans = self._check_nans(exp, context)
  1888.             if ans:
  1889.                 return ans
  1890.             
  1891.             if exp._isinfinity() or self._isinfinity():
  1892.                 if exp._isinfinity() and self._isinfinity():
  1893.                     return self
  1894.                 
  1895.                 if context is None:
  1896.                     context = getcontext()
  1897.                 
  1898.                 return context._raise_error(InvalidOperation, 'quantize with one INF')
  1899.             
  1900.         
  1901.         return self._rescale(exp._exp, rounding, context, watchexp)
  1902.  
  1903.     
  1904.     def same_quantum(self, other):
  1905.         '''Test whether self and other have the same exponent.
  1906.  
  1907.         same as self._exp == other._exp, except NaN == sNaN
  1908.         '''
  1909.         if self._is_special or other._is_special:
  1910.             if self._isnan() or other._isnan():
  1911.                 if self._isnan() and other._isnan():
  1912.                     pass
  1913.                 return True
  1914.             
  1915.             if self._isinfinity() or other._isinfinity():
  1916.                 if self._isinfinity() and other._isinfinity():
  1917.                     pass
  1918.                 return True
  1919.             
  1920.         
  1921.         return self._exp == other._exp
  1922.  
  1923.     
  1924.     def _rescale(self, exp, rounding = None, context = None, watchexp = 1):
  1925.         '''Rescales so that the exponent is exp.
  1926.  
  1927.         exp = exp to scale to (an integer)
  1928.         rounding = rounding version
  1929.         watchexp: if set (default) an error is returned if exp is greater
  1930.         than Emax or less than Etiny.
  1931.         '''
  1932.         if context is None:
  1933.             context = getcontext()
  1934.         
  1935.         if self._is_special:
  1936.             if self._isinfinity():
  1937.                 return context._raise_error(InvalidOperation, 'rescale with an INF')
  1938.             
  1939.             ans = self._check_nans(context = context)
  1940.             if ans:
  1941.                 return ans
  1942.             
  1943.         
  1944.         if watchexp:
  1945.             if context.Emax < exp or context.Etiny() > exp:
  1946.                 return context._raise_error(InvalidOperation, 'rescale(a, INF)')
  1947.             
  1948.         if not self:
  1949.             ans = Decimal(self)
  1950.             ans._int = (0,)
  1951.             ans._exp = exp
  1952.             return ans
  1953.         
  1954.         diff = self._exp - exp
  1955.         digits = len(self._int) + diff
  1956.         if watchexp and digits > context.prec:
  1957.             return context._raise_error(InvalidOperation, 'Rescale > prec')
  1958.         
  1959.         tmp = Decimal(self)
  1960.         tmp._int = (0,) + tmp._int
  1961.         digits += 1
  1962.         if digits < 0:
  1963.             tmp._exp = -digits + tmp._exp
  1964.             tmp._int = (0, 1)
  1965.             digits = 1
  1966.         
  1967.         tmp = tmp._round(digits, rounding, context = context)
  1968.         if tmp._int[0] == 0 and len(tmp._int) > 1:
  1969.             tmp._int = tmp._int[1:]
  1970.         
  1971.         tmp._exp = exp
  1972.         tmp_adjusted = tmp.adjusted()
  1973.         if tmp and tmp_adjusted < context.Emin:
  1974.             context._raise_error(Subnormal)
  1975.         elif tmp and tmp_adjusted > context.Emax:
  1976.             return context._raise_error(InvalidOperation, 'rescale(a, INF)')
  1977.         
  1978.         return tmp
  1979.  
  1980.     
  1981.     def to_integral(self, rounding = None, context = None):
  1982.         '''Rounds to the nearest integer, without raising inexact, rounded.'''
  1983.         if self._is_special:
  1984.             ans = self._check_nans(context = context)
  1985.             if ans:
  1986.                 return ans
  1987.             
  1988.         
  1989.         if self._exp >= 0:
  1990.             return self
  1991.         
  1992.         if context is None:
  1993.             context = getcontext()
  1994.         
  1995.         flags = context._ignore_flags(Rounded, Inexact)
  1996.         ans = self._rescale(0, rounding, context = context)
  1997.         context._regard_flags(flags)
  1998.         return ans
  1999.  
  2000.     
  2001.     def sqrt(self, context = None):
  2002.         '''Return the square root of self.
  2003.  
  2004.         Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
  2005.         Should quadratically approach the right answer.
  2006.         '''
  2007.         if self._is_special:
  2008.             ans = self._check_nans(context = context)
  2009.             if ans:
  2010.                 return ans
  2011.             
  2012.             if self._isinfinity() and self._sign == 0:
  2013.                 return Decimal(self)
  2014.             
  2015.         
  2016.         if not self:
  2017.             exp = self._exp // 2
  2018.             if self._sign == 1:
  2019.                 return Decimal((1, (0,), exp))
  2020.             else:
  2021.                 return Decimal((0, (0,), exp))
  2022.         
  2023.         if context is None:
  2024.             context = getcontext()
  2025.         
  2026.         if self._sign == 1:
  2027.             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
  2028.         
  2029.         tmp = Decimal(self)
  2030.         expadd = tmp._exp // 2
  2031.         if tmp._exp & 1:
  2032.             tmp._int += (0,)
  2033.             tmp._exp = 0
  2034.         else:
  2035.             tmp._exp = 0
  2036.         context = context._shallow_copy()
  2037.         flags = context._ignore_all_flags()
  2038.         firstprec = context.prec
  2039.         context.prec = 3
  2040.         Emax = context.Emax
  2041.         Emin = context.Emin
  2042.         context.Emax = DefaultContext.Emax
  2043.         context.Emin = DefaultContext.Emin
  2044.         half = Decimal('0.5')
  2045.         maxp = firstprec + 2
  2046.         rounding = context._set_rounding(ROUND_HALF_EVEN)
  2047.         while None:
  2048.             context.prec = min(2 * context.prec - 2, maxp)
  2049.             ans = half.__mul__(ans.__add__(tmp.__div__(ans, context = context), context = context), context = context)
  2050.             if context.prec == maxp:
  2051.                 break
  2052.                 continue
  2053.             continue
  2054.             context.prec = firstprec
  2055.             prevexp = ans.adjusted()
  2056.             ans = ans._round(context = context)
  2057.             context.prec = firstprec + 1
  2058.         lower = ans.__sub__(Decimal((0, (5,), ans._exp - 1)), context = context)
  2059.         context._set_rounding(ROUND_UP)
  2060.         if lower.__mul__(lower, context = context) > tmp:
  2061.             ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context = context)
  2062.         else:
  2063.             upper = ans.__add__(Decimal((0, (5,), ans._exp - 1)), context = context)
  2064.             context._set_rounding(ROUND_DOWN)
  2065.             if upper.__mul__(upper, context = context) < tmp:
  2066.                 ans = ans.__add__(Decimal((0, (1,), ans._exp)), context = context)
  2067.             
  2068.         ans._exp += expadd
  2069.         context.prec = firstprec
  2070.         context.rounding = rounding
  2071.         ans = ans._fix(context)
  2072.         rounding = context._set_rounding_decision(NEVER_ROUND)
  2073.         context.Emax = Emax
  2074.         context.Emin = Emin
  2075.         return ans._fix(context)
  2076.  
  2077.     
  2078.     def max(self, other, context = None):
  2079.         '''Returns the larger value.
  2080.  
  2081.         like max(self, other) except if one is not a number, returns
  2082.         NaN (and signals if one is sNaN).  Also rounds.
  2083.         '''
  2084.         other = _convert_other(other)
  2085.         if other is NotImplemented:
  2086.             return other
  2087.         
  2088.         if self._is_special or other._is_special:
  2089.             sn = self._isnan()
  2090.             on = other._isnan()
  2091.             if sn or on:
  2092.                 if on == 1 and sn != 2:
  2093.                     return self
  2094.                 
  2095.                 if sn == 1 and on != 2:
  2096.                     return other
  2097.                 
  2098.                 return self._check_nans(other, context)
  2099.             
  2100.         
  2101.         ans = self
  2102.         c = self.__cmp__(other)
  2103.         if c == 0:
  2104.             if self._sign != other._sign:
  2105.                 if self._sign:
  2106.                     ans = other
  2107.                 
  2108.             elif self._exp < other._exp and not (self._sign):
  2109.                 ans = other
  2110.             elif self._exp > other._exp and self._sign:
  2111.                 ans = other
  2112.             
  2113.         elif c == -1:
  2114.             ans = other
  2115.         
  2116.         if context is None:
  2117.             context = getcontext()
  2118.         
  2119.         if context._rounding_decision == ALWAYS_ROUND:
  2120.             return ans._fix(context)
  2121.         
  2122.         return ans
  2123.  
  2124.     
  2125.     def min(self, other, context = None):
  2126.         '''Returns the smaller value.
  2127.  
  2128.         like min(self, other) except if one is not a number, returns
  2129.         NaN (and signals if one is sNaN).  Also rounds.
  2130.         '''
  2131.         other = _convert_other(other)
  2132.         if other is NotImplemented:
  2133.             return other
  2134.         
  2135.         if self._is_special or other._is_special:
  2136.             sn = self._isnan()
  2137.             on = other._isnan()
  2138.             if sn or on:
  2139.                 if on == 1 and sn != 2:
  2140.                     return self
  2141.                 
  2142.                 if sn == 1 and on != 2:
  2143.                     return other
  2144.                 
  2145.                 return self._check_nans(other, context)
  2146.             
  2147.         
  2148.         ans = self
  2149.         c = self.__cmp__(other)
  2150.         if c == 0:
  2151.             if self._sign != other._sign:
  2152.                 if other._sign:
  2153.                     ans = other
  2154.                 
  2155.             elif self._exp > other._exp and not (self._sign):
  2156.                 ans = other
  2157.             elif self._exp < other._exp and self._sign:
  2158.                 ans = other
  2159.             
  2160.         elif c == 1:
  2161.             ans = other
  2162.         
  2163.         if context is None:
  2164.             context = getcontext()
  2165.         
  2166.         if context._rounding_decision == ALWAYS_ROUND:
  2167.             return ans._fix(context)
  2168.         
  2169.         return ans
  2170.  
  2171.     
  2172.     def _isinteger(self):
  2173.         '''Returns whether self is an integer'''
  2174.         if self._exp >= 0:
  2175.             return True
  2176.         
  2177.         rest = self._int[self._exp:]
  2178.         return rest == (0,) * len(rest)
  2179.  
  2180.     
  2181.     def _iseven(self):
  2182.         '''Returns 1 if self is even.  Assumes self is an integer.'''
  2183.         if self._exp > 0:
  2184.             return 1
  2185.         
  2186.         return self._int[-1 + self._exp] & 1 == 0
  2187.  
  2188.     
  2189.     def adjusted(self):
  2190.         '''Return the adjusted exponent of self'''
  2191.         
  2192.         try:
  2193.             return self._exp + len(self._int) - 1
  2194.         except TypeError:
  2195.             return 0
  2196.  
  2197.  
  2198.     
  2199.     def __reduce__(self):
  2200.         return (self.__class__, (str(self),))
  2201.  
  2202.     
  2203.     def __copy__(self):
  2204.         if type(self) == Decimal:
  2205.             return self
  2206.         
  2207.         return self.__class__(str(self))
  2208.  
  2209.     
  2210.     def __deepcopy__(self, memo):
  2211.         if type(self) == Decimal:
  2212.             return self
  2213.         
  2214.         return self.__class__(str(self))
  2215.  
  2216.  
  2217. rounding_functions = [] if name.startswith('_round_') else _[1]
  2218. for name in rounding_functions:
  2219.     globalname = name[1:].upper()
  2220.     val = globals()[globalname]
  2221.     Decimal._pick_rounding_function[val] = name
  2222.  
  2223. del name
  2224. del val
  2225. del globalname
  2226. del rounding_functions
  2227.  
  2228. class _ContextManager(object):
  2229.     '''Context manager class to support localcontext().
  2230.  
  2231.       Sets a copy of the supplied context in __enter__() and restores
  2232.       the previous decimal context in __exit__()
  2233.     '''
  2234.     
  2235.     def __init__(self, new_context):
  2236.         self.new_context = new_context.copy()
  2237.  
  2238.     
  2239.     def __enter__(self):
  2240.         self.saved_context = getcontext()
  2241.         setcontext(self.new_context)
  2242.         return self.new_context
  2243.  
  2244.     
  2245.     def __exit__(self, t, v, tb):
  2246.         setcontext(self.saved_context)
  2247.  
  2248.  
  2249.  
  2250. class Context(object):
  2251.     '''Contains the context for a Decimal instance.
  2252.  
  2253.     Contains:
  2254.     prec - precision (for use in rounding, division, square roots..)
  2255.     rounding - rounding type. (how you round)
  2256.     _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
  2257.     traps - If traps[exception] = 1, then the exception is
  2258.                     raised when it is caused.  Otherwise, a value is
  2259.                     substituted in.
  2260.     flags  - When an exception is caused, flags[exception] is incremented.
  2261.              (Whether or not the trap_enabler is set)
  2262.              Should be reset by user of Decimal instance.
  2263.     Emin -   Minimum exponent
  2264.     Emax -   Maximum exponent
  2265.     capitals -      If 1, 1*10^1 is printed as 1E+1.
  2266.                     If 0, printed as 1e1
  2267.     _clamp - If 1, change exponents if too high (Default 0)
  2268.     '''
  2269.     
  2270.     def __init__(self, prec = None, rounding = None, traps = None, flags = None, _rounding_decision = None, Emin = None, Emax = None, capitals = None, _clamp = 0, _ignored_flags = None):
  2271.         if flags is None:
  2272.             flags = []
  2273.         
  2274.         if _ignored_flags is None:
  2275.             _ignored_flags = []
  2276.         
  2277.         for name, val in locals().items():
  2278.             if val is None:
  2279.                 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
  2280.                 continue
  2281.             None if not isinstance(flags, dict) else dict if traps is not None and not isinstance(traps, dict) else dict
  2282.             setattr(self, name, val)
  2283.         
  2284.         del self.self
  2285.  
  2286.     
  2287.     def __repr__(self):
  2288.         '''Show the current context.'''
  2289.         s = []
  2290.         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
  2291.         ', '.join([] + [](_[1]) + ']')
  2292.         ', '.join([] + [](_[2]) + ']')
  2293.         return ', '.join(s) + ')'
  2294.  
  2295.     
  2296.     def clear_flags(self):
  2297.         '''Reset all flags to zero'''
  2298.         for flag in self.flags:
  2299.             self.flags[flag] = 0
  2300.         
  2301.  
  2302.     
  2303.     def _shallow_copy(self):
  2304.         '''Returns a shallow copy from self.'''
  2305.         nc = Context(self.prec, self.rounding, self.traps, self.flags, self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
  2306.         return nc
  2307.  
  2308.     
  2309.     def copy(self):
  2310.         '''Returns a deep copy from self.'''
  2311.         nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self._rounding_decision, self.Emin, self.Emax, self.capitals, self._clamp, self._ignored_flags)
  2312.         return nc
  2313.  
  2314.     __copy__ = copy
  2315.     
  2316.     def _raise_error(self, condition, explanation = None, *args):
  2317.         '''Handles an error
  2318.  
  2319.         If the flag is in _ignored_flags, returns the default response.
  2320.         Otherwise, it increments the flag, then, if the corresponding
  2321.         trap_enabler is set, it reaises the exception.  Otherwise, it returns
  2322.         the default value after incrementing the flag.
  2323.         '''
  2324.         error = _condition_map.get(condition, condition)
  2325.         if error in self._ignored_flags:
  2326.             return error().handle(self, *args)
  2327.         
  2328.         self.flags[error] += 1
  2329.         if not self.traps[error]:
  2330.             return condition().handle(self, *args)
  2331.         
  2332.         raise error, explanation
  2333.  
  2334.     
  2335.     def _ignore_all_flags(self):
  2336.         '''Ignore all flags, if they are raised'''
  2337.         return self._ignore_flags(*_signals)
  2338.  
  2339.     
  2340.     def _ignore_flags(self, *flags):
  2341.         '''Ignore the flags, if they are raised'''
  2342.         self._ignored_flags = self._ignored_flags + list(flags)
  2343.         return list(flags)
  2344.  
  2345.     
  2346.     def _regard_flags(self, *flags):
  2347.         '''Stop ignoring the flags, if they are raised'''
  2348.         if flags and isinstance(flags[0], (tuple, list)):
  2349.             flags = flags[0]
  2350.         
  2351.         for flag in flags:
  2352.             self._ignored_flags.remove(flag)
  2353.         
  2354.  
  2355.     
  2356.     def __hash__(self):
  2357.         '''A Context cannot be hashed.'''
  2358.         raise TypeError, 'Cannot hash a Context.'
  2359.  
  2360.     
  2361.     def Etiny(self):
  2362.         '''Returns Etiny (= Emin - prec + 1)'''
  2363.         return int((self.Emin - self.prec) + 1)
  2364.  
  2365.     
  2366.     def Etop(self):
  2367.         '''Returns maximum exponent (= Emax - prec + 1)'''
  2368.         return int((self.Emax - self.prec) + 1)
  2369.  
  2370.     
  2371.     def _set_rounding_decision(self, type):
  2372.         """Sets the rounding decision.
  2373.  
  2374.         Sets the rounding decision, and returns the current (previous)
  2375.         rounding decision.  Often used like:
  2376.  
  2377.         context = context._shallow_copy()
  2378.         # That so you don't change the calling context
  2379.         # if an error occurs in the middle (say DivisionImpossible is raised).
  2380.  
  2381.         rounding = context._set_rounding_decision(NEVER_ROUND)
  2382.         instance = instance / Decimal(2)
  2383.         context._set_rounding_decision(rounding)
  2384.  
  2385.         This will make it not round for that operation.
  2386.         """
  2387.         rounding = self._rounding_decision
  2388.         self._rounding_decision = type
  2389.         return rounding
  2390.  
  2391.     
  2392.     def _set_rounding(self, type):
  2393.         """Sets the rounding type.
  2394.  
  2395.         Sets the rounding type, and returns the current (previous)
  2396.         rounding type.  Often used like:
  2397.  
  2398.         context = context.copy()
  2399.         # so you don't change the calling context
  2400.         # if an error occurs in the middle.
  2401.         rounding = context._set_rounding(ROUND_UP)
  2402.         val = self.__sub__(other, context=context)
  2403.         context._set_rounding(rounding)
  2404.  
  2405.         This will make it round up for that operation.
  2406.         """
  2407.         rounding = self.rounding
  2408.         self.rounding = type
  2409.         return rounding
  2410.  
  2411.     
  2412.     def create_decimal(self, num = '0'):
  2413.         '''Creates a new Decimal instance but using self as context.'''
  2414.         d = Decimal(num, context = self)
  2415.         return d._fix(self)
  2416.  
  2417.     
  2418.     def abs(self, a):
  2419.         '''Returns the absolute value of the operand.
  2420.  
  2421.         If the operand is negative, the result is the same as using the minus
  2422.         operation on the operand. Otherwise, the result is the same as using
  2423.         the plus operation on the operand.
  2424.  
  2425.         >>> ExtendedContext.abs(Decimal(\'2.1\'))
  2426.         Decimal("2.1")
  2427.         >>> ExtendedContext.abs(Decimal(\'-100\'))
  2428.         Decimal("100")
  2429.         >>> ExtendedContext.abs(Decimal(\'101.5\'))
  2430.         Decimal("101.5")
  2431.         >>> ExtendedContext.abs(Decimal(\'-101.5\'))
  2432.         Decimal("101.5")
  2433.         '''
  2434.         return a.__abs__(context = self)
  2435.  
  2436.     
  2437.     def add(self, a, b):
  2438.         '''Return the sum of the two operands.
  2439.  
  2440.         >>> ExtendedContext.add(Decimal(\'12\'), Decimal(\'7.00\'))
  2441.         Decimal("19.00")
  2442.         >>> ExtendedContext.add(Decimal(\'1E+2\'), Decimal(\'1.01E+4\'))
  2443.         Decimal("1.02E+4")
  2444.         '''
  2445.         return a.__add__(b, context = self)
  2446.  
  2447.     
  2448.     def _apply(self, a):
  2449.         return str(a._fix(self))
  2450.  
  2451.     
  2452.     def compare(self, a, b):
  2453.         '''Compares values numerically.
  2454.  
  2455.         If the signs of the operands differ, a value representing each operand
  2456.         (\'-1\' if the operand is less than zero, \'0\' if the operand is zero or
  2457.         negative zero, or \'1\' if the operand is greater than zero) is used in
  2458.         place of that operand for the comparison instead of the actual
  2459.         operand.
  2460.  
  2461.         The comparison is then effected by subtracting the second operand from
  2462.         the first and then returning a value according to the result of the
  2463.         subtraction: \'-1\' if the result is less than zero, \'0\' if the result is
  2464.         zero or negative zero, or \'1\' if the result is greater than zero.
  2465.  
  2466.         >>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'3\'))
  2467.         Decimal("-1")
  2468.         >>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'2.1\'))
  2469.         Decimal("0")
  2470.         >>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'2.10\'))
  2471.         Decimal("0")
  2472.         >>> ExtendedContext.compare(Decimal(\'3\'), Decimal(\'2.1\'))
  2473.         Decimal("1")
  2474.         >>> ExtendedContext.compare(Decimal(\'2.1\'), Decimal(\'-3\'))
  2475.         Decimal("1")
  2476.         >>> ExtendedContext.compare(Decimal(\'-3\'), Decimal(\'2.1\'))
  2477.         Decimal("-1")
  2478.         '''
  2479.         return a.compare(b, context = self)
  2480.  
  2481.     
  2482.     def divide(self, a, b):
  2483.         '''Decimal division in a specified context.
  2484.  
  2485.         >>> ExtendedContext.divide(Decimal(\'1\'), Decimal(\'3\'))
  2486.         Decimal("0.333333333")
  2487.         >>> ExtendedContext.divide(Decimal(\'2\'), Decimal(\'3\'))
  2488.         Decimal("0.666666667")
  2489.         >>> ExtendedContext.divide(Decimal(\'5\'), Decimal(\'2\'))
  2490.         Decimal("2.5")
  2491.         >>> ExtendedContext.divide(Decimal(\'1\'), Decimal(\'10\'))
  2492.         Decimal("0.1")
  2493.         >>> ExtendedContext.divide(Decimal(\'12\'), Decimal(\'12\'))
  2494.         Decimal("1")
  2495.         >>> ExtendedContext.divide(Decimal(\'8.00\'), Decimal(\'2\'))
  2496.         Decimal("4.00")
  2497.         >>> ExtendedContext.divide(Decimal(\'2.400\'), Decimal(\'2.0\'))
  2498.         Decimal("1.20")
  2499.         >>> ExtendedContext.divide(Decimal(\'1000\'), Decimal(\'100\'))
  2500.         Decimal("10")
  2501.         >>> ExtendedContext.divide(Decimal(\'1000\'), Decimal(\'1\'))
  2502.         Decimal("1000")
  2503.         >>> ExtendedContext.divide(Decimal(\'2.40E+6\'), Decimal(\'2\'))
  2504.         Decimal("1.20E+6")
  2505.         '''
  2506.         return a.__div__(b, context = self)
  2507.  
  2508.     
  2509.     def divide_int(self, a, b):
  2510.         '''Divides two numbers and returns the integer part of the result.
  2511.  
  2512.         >>> ExtendedContext.divide_int(Decimal(\'2\'), Decimal(\'3\'))
  2513.         Decimal("0")
  2514.         >>> ExtendedContext.divide_int(Decimal(\'10\'), Decimal(\'3\'))
  2515.         Decimal("3")
  2516.         >>> ExtendedContext.divide_int(Decimal(\'1\'), Decimal(\'0.3\'))
  2517.         Decimal("3")
  2518.         '''
  2519.         return a.__floordiv__(b, context = self)
  2520.  
  2521.     
  2522.     def divmod(self, a, b):
  2523.         return a.__divmod__(b, context = self)
  2524.  
  2525.     
  2526.     def max(self, a, b):
  2527.         '''max compares two values numerically and returns the maximum.
  2528.  
  2529.         If either operand is a NaN then the general rules apply.
  2530.         Otherwise, the operands are compared as as though by the compare
  2531.         operation. If they are numerically equal then the left-hand operand
  2532.         is chosen as the result. Otherwise the maximum (closer to positive
  2533.         infinity) of the two operands is chosen as the result.
  2534.  
  2535.         >>> ExtendedContext.max(Decimal(\'3\'), Decimal(\'2\'))
  2536.         Decimal("3")
  2537.         >>> ExtendedContext.max(Decimal(\'-10\'), Decimal(\'3\'))
  2538.         Decimal("3")
  2539.         >>> ExtendedContext.max(Decimal(\'1.0\'), Decimal(\'1\'))
  2540.         Decimal("1")
  2541.         >>> ExtendedContext.max(Decimal(\'7\'), Decimal(\'NaN\'))
  2542.         Decimal("7")
  2543.         '''
  2544.         return a.max(b, context = self)
  2545.  
  2546.     
  2547.     def min(self, a, b):
  2548.         '''min compares two values numerically and returns the minimum.
  2549.  
  2550.         If either operand is a NaN then the general rules apply.
  2551.         Otherwise, the operands are compared as as though by the compare
  2552.         operation. If they are numerically equal then the left-hand operand
  2553.         is chosen as the result. Otherwise the minimum (closer to negative
  2554.         infinity) of the two operands is chosen as the result.
  2555.  
  2556.         >>> ExtendedContext.min(Decimal(\'3\'), Decimal(\'2\'))
  2557.         Decimal("2")
  2558.         >>> ExtendedContext.min(Decimal(\'-10\'), Decimal(\'3\'))
  2559.         Decimal("-10")
  2560.         >>> ExtendedContext.min(Decimal(\'1.0\'), Decimal(\'1\'))
  2561.         Decimal("1.0")
  2562.         >>> ExtendedContext.min(Decimal(\'7\'), Decimal(\'NaN\'))
  2563.         Decimal("7")
  2564.         '''
  2565.         return a.min(b, context = self)
  2566.  
  2567.     
  2568.     def minus(self, a):
  2569.         '''Minus corresponds to unary prefix minus in Python.
  2570.  
  2571.         The operation is evaluated using the same rules as subtract; the
  2572.         operation minus(a) is calculated as subtract(\'0\', a) where the \'0\'
  2573.         has the same exponent as the operand.
  2574.  
  2575.         >>> ExtendedContext.minus(Decimal(\'1.3\'))
  2576.         Decimal("-1.3")
  2577.         >>> ExtendedContext.minus(Decimal(\'-1.3\'))
  2578.         Decimal("1.3")
  2579.         '''
  2580.         return a.__neg__(context = self)
  2581.  
  2582.     
  2583.     def multiply(self, a, b):
  2584.         '''multiply multiplies two operands.
  2585.  
  2586.         If either operand is a special value then the general rules apply.
  2587.         Otherwise, the operands are multiplied together (\'long multiplication\'),
  2588.         resulting in a number which may be as long as the sum of the lengths
  2589.         of the two operands.
  2590.  
  2591.         >>> ExtendedContext.multiply(Decimal(\'1.20\'), Decimal(\'3\'))
  2592.         Decimal("3.60")
  2593.         >>> ExtendedContext.multiply(Decimal(\'7\'), Decimal(\'3\'))
  2594.         Decimal("21")
  2595.         >>> ExtendedContext.multiply(Decimal(\'0.9\'), Decimal(\'0.8\'))
  2596.         Decimal("0.72")
  2597.         >>> ExtendedContext.multiply(Decimal(\'0.9\'), Decimal(\'-0\'))
  2598.         Decimal("-0.0")
  2599.         >>> ExtendedContext.multiply(Decimal(\'654321\'), Decimal(\'654321\'))
  2600.         Decimal("4.28135971E+11")
  2601.         '''
  2602.         return a.__mul__(b, context = self)
  2603.  
  2604.     
  2605.     def normalize(self, a):
  2606.         '''normalize reduces an operand to its simplest form.
  2607.  
  2608.         Essentially a plus operation with all trailing zeros removed from the
  2609.         result.
  2610.  
  2611.         >>> ExtendedContext.normalize(Decimal(\'2.1\'))
  2612.         Decimal("2.1")
  2613.         >>> ExtendedContext.normalize(Decimal(\'-2.0\'))
  2614.         Decimal("-2")
  2615.         >>> ExtendedContext.normalize(Decimal(\'1.200\'))
  2616.         Decimal("1.2")
  2617.         >>> ExtendedContext.normalize(Decimal(\'-120\'))
  2618.         Decimal("-1.2E+2")
  2619.         >>> ExtendedContext.normalize(Decimal(\'120.00\'))
  2620.         Decimal("1.2E+2")
  2621.         >>> ExtendedContext.normalize(Decimal(\'0.00\'))
  2622.         Decimal("0")
  2623.         '''
  2624.         return a.normalize(context = self)
  2625.  
  2626.     
  2627.     def plus(self, a):
  2628.         '''Plus corresponds to unary prefix plus in Python.
  2629.  
  2630.         The operation is evaluated using the same rules as add; the
  2631.         operation plus(a) is calculated as add(\'0\', a) where the \'0\'
  2632.         has the same exponent as the operand.
  2633.  
  2634.         >>> ExtendedContext.plus(Decimal(\'1.3\'))
  2635.         Decimal("1.3")
  2636.         >>> ExtendedContext.plus(Decimal(\'-1.3\'))
  2637.         Decimal("-1.3")
  2638.         '''
  2639.         return a.__pos__(context = self)
  2640.  
  2641.     
  2642.     def power(self, a, b, modulo = None):
  2643.         '''Raises a to the power of b, to modulo if given.
  2644.  
  2645.         The right-hand operand must be a whole number whose integer part (after
  2646.         any exponent has been applied) has no more than 9 digits and whose
  2647.         fractional part (if any) is all zeros before any rounding. The operand
  2648.         may be positive, negative, or zero; if negative, the absolute value of
  2649.         the power is used, and the left-hand operand is inverted (divided into
  2650.         1) before use.
  2651.  
  2652.         If the increased precision needed for the intermediate calculations
  2653.         exceeds the capabilities of the implementation then an Invalid operation
  2654.         condition is raised.
  2655.  
  2656.         If, when raising to a negative power, an underflow occurs during the
  2657.         division into 1, the operation is not halted at that point but
  2658.         continues.
  2659.  
  2660.         >>> ExtendedContext.power(Decimal(\'2\'), Decimal(\'3\'))
  2661.         Decimal("8")
  2662.         >>> ExtendedContext.power(Decimal(\'2\'), Decimal(\'-3\'))
  2663.         Decimal("0.125")
  2664.         >>> ExtendedContext.power(Decimal(\'1.7\'), Decimal(\'8\'))
  2665.         Decimal("69.7575744")
  2666.         >>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'-2\'))
  2667.         Decimal("0")
  2668.         >>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'-1\'))
  2669.         Decimal("0")
  2670.         >>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'0\'))
  2671.         Decimal("1")
  2672.         >>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'1\'))
  2673.         Decimal("Infinity")
  2674.         >>> ExtendedContext.power(Decimal(\'Infinity\'), Decimal(\'2\'))
  2675.         Decimal("Infinity")
  2676.         >>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'-2\'))
  2677.         Decimal("0")
  2678.         >>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'-1\'))
  2679.         Decimal("-0")
  2680.         >>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'0\'))
  2681.         Decimal("1")
  2682.         >>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'1\'))
  2683.         Decimal("-Infinity")
  2684.         >>> ExtendedContext.power(Decimal(\'-Infinity\'), Decimal(\'2\'))
  2685.         Decimal("Infinity")
  2686.         >>> ExtendedContext.power(Decimal(\'0\'), Decimal(\'0\'))
  2687.         Decimal("NaN")
  2688.         '''
  2689.         return a.__pow__(b, modulo, context = self)
  2690.  
  2691.     
  2692.     def quantize(self, a, b):
  2693.         '''Returns a value equal to \'a\' (rounded) and having the exponent of \'b\'.
  2694.  
  2695.         The coefficient of the result is derived from that of the left-hand
  2696.         operand. It may be rounded using the current rounding setting (if the
  2697.         exponent is being increased), multiplied by a positive power of ten (if
  2698.         the exponent is being decreased), or is unchanged (if the exponent is
  2699.         already equal to that of the right-hand operand).
  2700.  
  2701.         Unlike other operations, if the length of the coefficient after the
  2702.         quantize operation would be greater than precision then an Invalid
  2703.         operation condition is raised. This guarantees that, unless there is an
  2704.         error condition, the exponent of the result of a quantize is always
  2705.         equal to that of the right-hand operand.
  2706.  
  2707.         Also unlike other operations, quantize will never raise Underflow, even
  2708.         if the result is subnormal and inexact.
  2709.  
  2710.         >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.001\'))
  2711.         Decimal("2.170")
  2712.         >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.01\'))
  2713.         Decimal("2.17")
  2714.         >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'0.1\'))
  2715.         Decimal("2.2")
  2716.         >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'1e+0\'))
  2717.         Decimal("2")
  2718.         >>> ExtendedContext.quantize(Decimal(\'2.17\'), Decimal(\'1e+1\'))
  2719.         Decimal("0E+1")
  2720.         >>> ExtendedContext.quantize(Decimal(\'-Inf\'), Decimal(\'Infinity\'))
  2721.         Decimal("-Infinity")
  2722.         >>> ExtendedContext.quantize(Decimal(\'2\'), Decimal(\'Infinity\'))
  2723.         Decimal("NaN")
  2724.         >>> ExtendedContext.quantize(Decimal(\'-0.1\'), Decimal(\'1\'))
  2725.         Decimal("-0")
  2726.         >>> ExtendedContext.quantize(Decimal(\'-0\'), Decimal(\'1e+5\'))
  2727.         Decimal("-0E+5")
  2728.         >>> ExtendedContext.quantize(Decimal(\'+35236450.6\'), Decimal(\'1e-2\'))
  2729.         Decimal("NaN")
  2730.         >>> ExtendedContext.quantize(Decimal(\'-35236450.6\'), Decimal(\'1e-2\'))
  2731.         Decimal("NaN")
  2732.         >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e-1\'))
  2733.         Decimal("217.0")
  2734.         >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e-0\'))
  2735.         Decimal("217")
  2736.         >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e+1\'))
  2737.         Decimal("2.2E+2")
  2738.         >>> ExtendedContext.quantize(Decimal(\'217\'), Decimal(\'1e+2\'))
  2739.         Decimal("2E+2")
  2740.         '''
  2741.         return a.quantize(b, context = self)
  2742.  
  2743.     
  2744.     def remainder(self, a, b):
  2745.         '''Returns the remainder from integer division.
  2746.  
  2747.         The result is the residue of the dividend after the operation of
  2748.         calculating integer division as described for divide-integer, rounded to
  2749.         precision digits if necessary. The sign of the result, if non-zero, is
  2750.         the same as that of the original dividend.
  2751.  
  2752.         This operation will fail under the same conditions as integer division
  2753.         (that is, if integer division on the same two operands would fail, the
  2754.         remainder cannot be calculated).
  2755.  
  2756.         >>> ExtendedContext.remainder(Decimal(\'2.1\'), Decimal(\'3\'))
  2757.         Decimal("2.1")
  2758.         >>> ExtendedContext.remainder(Decimal(\'10\'), Decimal(\'3\'))
  2759.         Decimal("1")
  2760.         >>> ExtendedContext.remainder(Decimal(\'-10\'), Decimal(\'3\'))
  2761.         Decimal("-1")
  2762.         >>> ExtendedContext.remainder(Decimal(\'10.2\'), Decimal(\'1\'))
  2763.         Decimal("0.2")
  2764.         >>> ExtendedContext.remainder(Decimal(\'10\'), Decimal(\'0.3\'))
  2765.         Decimal("0.1")
  2766.         >>> ExtendedContext.remainder(Decimal(\'3.6\'), Decimal(\'1.3\'))
  2767.         Decimal("1.0")
  2768.         '''
  2769.         return a.__mod__(b, context = self)
  2770.  
  2771.     
  2772.     def remainder_near(self, a, b):
  2773.         '''Returns to be "a - b * n", where n is the integer nearest the exact
  2774.         value of "x / b" (if two integers are equally near then the even one
  2775.         is chosen). If the result is equal to 0 then its sign will be the
  2776.         sign of a.
  2777.  
  2778.         This operation will fail under the same conditions as integer division
  2779.         (that is, if integer division on the same two operands would fail, the
  2780.         remainder cannot be calculated).
  2781.  
  2782.         >>> ExtendedContext.remainder_near(Decimal(\'2.1\'), Decimal(\'3\'))
  2783.         Decimal("-0.9")
  2784.         >>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'6\'))
  2785.         Decimal("-2")
  2786.         >>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'3\'))
  2787.         Decimal("1")
  2788.         >>> ExtendedContext.remainder_near(Decimal(\'-10\'), Decimal(\'3\'))
  2789.         Decimal("-1")
  2790.         >>> ExtendedContext.remainder_near(Decimal(\'10.2\'), Decimal(\'1\'))
  2791.         Decimal("0.2")
  2792.         >>> ExtendedContext.remainder_near(Decimal(\'10\'), Decimal(\'0.3\'))
  2793.         Decimal("0.1")
  2794.         >>> ExtendedContext.remainder_near(Decimal(\'3.6\'), Decimal(\'1.3\'))
  2795.         Decimal("-0.3")
  2796.         '''
  2797.         return a.remainder_near(b, context = self)
  2798.  
  2799.     
  2800.     def same_quantum(self, a, b):
  2801.         """Returns True if the two operands have the same exponent.
  2802.  
  2803.         The result is never affected by either the sign or the coefficient of
  2804.         either operand.
  2805.  
  2806.         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
  2807.         False
  2808.         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
  2809.         True
  2810.         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
  2811.         False
  2812.         >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
  2813.         True
  2814.         """
  2815.         return a.same_quantum(b)
  2816.  
  2817.     
  2818.     def sqrt(self, a):
  2819.         '''Returns the square root of a non-negative number to context precision.
  2820.  
  2821.         If the result must be inexact, it is rounded using the round-half-even
  2822.         algorithm.
  2823.  
  2824.         >>> ExtendedContext.sqrt(Decimal(\'0\'))
  2825.         Decimal("0")
  2826.         >>> ExtendedContext.sqrt(Decimal(\'-0\'))
  2827.         Decimal("-0")
  2828.         >>> ExtendedContext.sqrt(Decimal(\'0.39\'))
  2829.         Decimal("0.624499800")
  2830.         >>> ExtendedContext.sqrt(Decimal(\'100\'))
  2831.         Decimal("10")
  2832.         >>> ExtendedContext.sqrt(Decimal(\'1\'))
  2833.         Decimal("1")
  2834.         >>> ExtendedContext.sqrt(Decimal(\'1.0\'))
  2835.         Decimal("1.0")
  2836.         >>> ExtendedContext.sqrt(Decimal(\'1.00\'))
  2837.         Decimal("1.0")
  2838.         >>> ExtendedContext.sqrt(Decimal(\'7\'))
  2839.         Decimal("2.64575131")
  2840.         >>> ExtendedContext.sqrt(Decimal(\'10\'))
  2841.         Decimal("3.16227766")
  2842.         >>> ExtendedContext.prec
  2843.         9
  2844.         '''
  2845.         return a.sqrt(context = self)
  2846.  
  2847.     
  2848.     def subtract(self, a, b):
  2849.         '''Return the difference between the two operands.
  2850.  
  2851.         >>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'1.07\'))
  2852.         Decimal("0.23")
  2853.         >>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'1.30\'))
  2854.         Decimal("0.00")
  2855.         >>> ExtendedContext.subtract(Decimal(\'1.3\'), Decimal(\'2.07\'))
  2856.         Decimal("-0.77")
  2857.         '''
  2858.         return a.__sub__(b, context = self)
  2859.  
  2860.     
  2861.     def to_eng_string(self, a):
  2862.         '''Converts a number to a string, using scientific notation.
  2863.  
  2864.         The operation is not affected by the context.
  2865.         '''
  2866.         return a.to_eng_string(context = self)
  2867.  
  2868.     
  2869.     def to_sci_string(self, a):
  2870.         '''Converts a number to a string, using scientific notation.
  2871.  
  2872.         The operation is not affected by the context.
  2873.         '''
  2874.         return a.__str__(context = self)
  2875.  
  2876.     
  2877.     def to_integral(self, a):
  2878.         '''Rounds to an integer.
  2879.  
  2880.         When the operand has a negative exponent, the result is the same
  2881.         as using the quantize() operation using the given operand as the
  2882.         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
  2883.         of the operand as the precision setting, except that no flags will
  2884.         be set. The rounding mode is taken from the context.
  2885.  
  2886.         >>> ExtendedContext.to_integral(Decimal(\'2.1\'))
  2887.         Decimal("2")
  2888.         >>> ExtendedContext.to_integral(Decimal(\'100\'))
  2889.         Decimal("100")
  2890.         >>> ExtendedContext.to_integral(Decimal(\'100.0\'))
  2891.         Decimal("100")
  2892.         >>> ExtendedContext.to_integral(Decimal(\'101.5\'))
  2893.         Decimal("102")
  2894.         >>> ExtendedContext.to_integral(Decimal(\'-101.5\'))
  2895.         Decimal("-102")
  2896.         >>> ExtendedContext.to_integral(Decimal(\'10E+5\'))
  2897.         Decimal("1.0E+6")
  2898.         >>> ExtendedContext.to_integral(Decimal(\'7.89E+77\'))
  2899.         Decimal("7.89E+77")
  2900.         >>> ExtendedContext.to_integral(Decimal(\'-Inf\'))
  2901.         Decimal("-Infinity")
  2902.         '''
  2903.         return a.to_integral(context = self)
  2904.  
  2905.  
  2906.  
  2907. class _WorkRep(object):
  2908.     __slots__ = ('sign', 'int', 'exp')
  2909.     
  2910.     def __init__(self, value = None):
  2911.         if value is None:
  2912.             self.sign = None
  2913.             self.int = 0
  2914.             self.exp = None
  2915.         elif isinstance(value, Decimal):
  2916.             self.sign = value._sign
  2917.             cum = 0
  2918.             for digit in value._int:
  2919.                 cum = cum * 10 + digit
  2920.             
  2921.             self.int = cum
  2922.             self.exp = value._exp
  2923.         else:
  2924.             self.sign = value[0]
  2925.             self.int = value[1]
  2926.             self.exp = value[2]
  2927.  
  2928.     
  2929.     def __repr__(self):
  2930.         return '(%r, %r, %r)' % (self.sign, self.int, self.exp)
  2931.  
  2932.     __str__ = __repr__
  2933.  
  2934.  
  2935. def _normalize(op1, op2, shouldround = 0, prec = 0):
  2936.     '''Normalizes op1, op2 to have the same exp and length of coefficient.
  2937.  
  2938.     Done during addition.
  2939.     '''
  2940.     numdigits = int(op1.exp - op2.exp)
  2941.     if numdigits < 0:
  2942.         numdigits = -numdigits
  2943.         tmp = op2
  2944.         other = op1
  2945.     else:
  2946.         tmp = op1
  2947.         other = op2
  2948.     if shouldround and numdigits > prec + 1:
  2949.         tmp_len = len(str(tmp.int))
  2950.         other_len = len(str(other.int))
  2951.         if numdigits > other_len + prec + 1 - tmp_len:
  2952.             extend = prec + 2 - tmp_len
  2953.             if extend <= 0:
  2954.                 extend = 1
  2955.             
  2956.             tmp.int *= 10 ** extend
  2957.             tmp.exp -= extend
  2958.             other.int = 1
  2959.             other.exp = tmp.exp
  2960.             return (op1, op2)
  2961.         
  2962.     
  2963.     tmp.int *= 10 ** numdigits
  2964.     tmp.exp -= numdigits
  2965.     return (op1, op2)
  2966.  
  2967.  
  2968. def _adjust_coefficients(op1, op2):
  2969.     '''Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
  2970.  
  2971.     Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
  2972.  
  2973.     Used on _WorkRep instances during division.
  2974.     '''
  2975.     adjust = 0
  2976.     while op2.int > op1.int:
  2977.         op1.int *= 10
  2978.         op1.exp -= 1
  2979.         adjust += 1
  2980.         continue
  2981.         op1
  2982.     while op1.int >= 10 * op2.int:
  2983.         op2.int *= 10
  2984.         op2.exp -= 1
  2985.         adjust -= 1
  2986.         continue
  2987.         op2
  2988.     return (op1, op2, adjust)
  2989.  
  2990.  
  2991. def _convert_other(other):
  2992.     """Convert other to Decimal.
  2993.  
  2994.     Verifies that it's ok to use in an implicit construction.
  2995.     """
  2996.     if isinstance(other, Decimal):
  2997.         return other
  2998.     
  2999.     if isinstance(other, (int, long)):
  3000.         return Decimal(other)
  3001.     
  3002.     return NotImplemented
  3003.  
  3004. _infinity_map = {
  3005.     'inf': 1,
  3006.     'infinity': 1,
  3007.     '+inf': 1,
  3008.     '+infinity': 1,
  3009.     '-inf': -1,
  3010.     '-infinity': -1 }
  3011.  
  3012. def _isinfinity(num):
  3013.     '''Determines whether a string or float is infinity.
  3014.  
  3015.     +1 for negative infinity; 0 for finite ; +1 for positive infinity
  3016.     '''
  3017.     num = str(num).lower()
  3018.     return _infinity_map.get(num, 0)
  3019.  
  3020.  
  3021. def _isnan(num):
  3022.     '''Determines whether a string or float is NaN
  3023.  
  3024.     (1, sign, diagnostic info as string) => NaN
  3025.     (2, sign, diagnostic info as string) => sNaN
  3026.     0 => not a NaN
  3027.     '''
  3028.     num = str(num).lower()
  3029.     if not num:
  3030.         return 0
  3031.     
  3032.     sign = 0
  3033.     if num[0] == '+':
  3034.         num = num[1:]
  3035.     elif num[0] == '-':
  3036.         num = num[1:]
  3037.         sign = 1
  3038.     
  3039.     if num.startswith('nan'):
  3040.         if len(num) > 3 and not num[3:].isdigit():
  3041.             return 0
  3042.         
  3043.         return (1, sign, num[3:].lstrip('0'))
  3044.     
  3045.     if num.startswith('snan'):
  3046.         if len(num) > 4 and not num[4:].isdigit():
  3047.             return 0
  3048.         
  3049.         return (2, sign, num[4:].lstrip('0'))
  3050.     
  3051.     return 0
  3052.  
  3053. DefaultContext = Context(prec = 28, rounding = ROUND_HALF_EVEN, traps = [
  3054.     DivisionByZero,
  3055.     Overflow,
  3056.     InvalidOperation], flags = [], _rounding_decision = ALWAYS_ROUND, Emax = 999999999, Emin = -999999999, capitals = 1)
  3057. BasicContext = Context(prec = 9, rounding = ROUND_HALF_UP, traps = [
  3058.     DivisionByZero,
  3059.     Overflow,
  3060.     InvalidOperation,
  3061.     Clamped,
  3062.     Underflow], flags = [])
  3063. ExtendedContext = Context(prec = 9, rounding = ROUND_HALF_EVEN, traps = [], flags = [])
  3064. Inf = Decimal('Inf')
  3065. negInf = Decimal('-Inf')
  3066. Infsign = (Inf, negInf)
  3067. NaN = Decimal('NaN')
  3068. import re
  3069. _parser = re.compile('\n#    \\s*\n    (?P<sign>[-+])?\n    (\n        (?P<int>\\d+) (\\. (?P<frac>\\d*))?\n    |\n        \\. (?P<onlyfrac>\\d+)\n    )\n    ([eE](?P<exp>[-+]? \\d+))?\n#    \\s*\n    $\n', re.VERBOSE).match
  3070. del re
  3071.  
  3072. def _string2exact(s):
  3073.     m = _parser(s)
  3074.     if m is None:
  3075.         raise ValueError('invalid literal for Decimal: %r' % s)
  3076.     
  3077.     if m.group('sign') == '-':
  3078.         sign = 1
  3079.     else:
  3080.         sign = 0
  3081.     exp = m.group('exp')
  3082.     if exp is None:
  3083.         exp = 0
  3084.     else:
  3085.         exp = int(exp)
  3086.     intpart = m.group('int')
  3087.     if intpart is None:
  3088.         intpart = ''
  3089.         fracpart = m.group('onlyfrac')
  3090.     else:
  3091.         fracpart = m.group('frac')
  3092.         if fracpart is None:
  3093.             fracpart = ''
  3094.         
  3095.     exp -= len(fracpart)
  3096.     mantissa = intpart + fracpart
  3097.     tmp = map(int, mantissa)
  3098.     backup = tmp
  3099.     while tmp and tmp[0] == 0:
  3100.         del tmp[0]
  3101.     if not tmp:
  3102.         if backup:
  3103.             return (sign, tuple(backup), exp)
  3104.         
  3105.         return (sign, (0,), exp)
  3106.     
  3107.     mantissa = tuple(tmp)
  3108.     return (sign, mantissa, exp)
  3109.  
  3110. if __name__ == '__main__':
  3111.     import doctest
  3112.     import sys
  3113.     doctest.testmod(sys.modules[__name__])
  3114.  
  3115.